flutter 对象的状态未正确存储

mzsu5hc0  于 2023-01-14  发布在  Flutter
关注(0)|答案(1)|浏览(150)

我想将对象标记为收藏夹。
我有一个对象<RobotAnimation>的列表,显示在ListView中。该类有两个字段:titleisFavorite。将对象标记为收藏夹可以正常工作,但在存储该状态时会出现问题。当我搜索所有项目时,在将项目选择为收藏夹后,我的收藏夹项目不会被记住。看起来该状态正在被丢弃。
我可以做些什么来解决这个问题?
事情是这样的:

下面是我的代码:

class RobotAnimation {
  String title;
  bool isFavorite;

  RobotAnimation({required this.title, this.isFavorite = false});

  @override
  String toString() {
    return '{Title: $title, isFavortite: $isFavorite}';
  }
}

class Animations extends StatefulWidget {
  const Animations({super.key});

  @override
  State<Animations> createState() => _AnimationsState();
}

class _AnimationsState extends State<Animations> with TickerProviderStateMixin {
  late TabController _tabController;

  List<RobotAnimation> animations = [];
  List<RobotAnimation> favoriteAnimations = [];
  List<String> results = store.state.animations;
  List<String> defaultFavorites = [];

  List<RobotAnimation> getAnimationList(
      List<String> animations, List<String> favorites) {
    List<RobotAnimation> robotAnimations = [];
    for (var animation in animations) {
      bool isFav = false;
      for (var favorite in favorites) {
        if (favorite == animation) {
          isFav = true;
        }
      }
      robotAnimations.add(RobotAnimation(title: animation, isFavorite: isFav));
    }
    return robotAnimations;
  }

  List<RobotAnimation> filterFavorites() {
    List<RobotAnimation> filtered = favoriteAnimations;
    animations.where((element) => element.isFavorite == true).toList();

    return filtered;
  }

  void filterSearchResults(String query) {
    List<RobotAnimation> searchList =
        getAnimationList(results, defaultFavorites);
    log('query: $query');

    List<RobotAnimation> filteredList = searchList
        .where((element) =>
            element.title.toLowerCase().contains(query.toLowerCase()))
        .toList();

    log(searchList.toString());

    log(filteredList.toString());
    setState(() => animations = filteredList);
  }

  @override
  void initState() {
    animations = getAnimationList(results, defaultFavorites);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return StoreConnector<AppState, _Props>(
      converter: (store) => _mapStateToProps(store),
      builder: (_, props) {
        return Scaffold(
          body: TabBarView(
            ...
            children: [
              Container(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  children: [
                    TextField(
                      onChanged: filterSearchResults,
                      decoration: const InputDecoration(
                        labelText: 'Search',
                        hintText: 'Search animation',
                        prefixIcon: Icon(Icons.search),
                      ),
                    ),
                    Expanded(
                      child: ListView.separated(
                        itemCount: animations.length,
                        separatorBuilder: (context, index) => const Divider(),
                        itemBuilder: (context, index) {
                          return ListTile(
                            onTap: () {
                              props.socket?.animation(IAnimation(
                                  animation: animations[index].title));
                            },
                            title: ExtendedText(
                              animations[index].title,
                              maxLines: 1,
                              overflowWidget: const TextOverflowWidget(
                                position: TextOverflowPosition.middle,
                                align: TextOverflowAlign.center,
                                child: Text(
                                  '...',
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            ),
                            trailing: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                IconButton(
                                  onPressed: () {
                                    setState(() {
                                      animations[index].isFavorite
                                          ? animations[index].isFavorite = false
                                          : animations[index].isFavorite = true;
                                    });
                                  },
                                  icon: animations[index].isFavorite
                                      ? Icon(
                                          Icons.favorite,
                                          color: Colors.red.shade500,
                                        )
                                      : Icon(
                                          Icons.favorite_border,
                                          color: Colors.grey.shade500,
                                        ),
                                ),
                              ],
                            ),
                          );
                        },
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}

class _Props {
  final Connection? socket;
  final List<String> animations;

  _Props({
    required this.socket,
    required this.animations,
  });
}

_Props _mapStateToProps(Store<AppState> store) {
  return _Props(
    socket: store.state.socket,
    animations: store.state.animations,
  );
}
nwwlzxa7

nwwlzxa71#

在您的IconButtononPressed中尝试此操作-方法:

setState(() {
  if (animations[index].isFavorite) {
    animations[index].isFavorite = false
    defaultFavorites.remove(animations[index].title)
  } else {
    animations[index].isFavorite = true;
    defaultFavorites.add(animations[index].title)
  }
});

看起来您总是基于两个列表List<String>生成新的动画列表。

相关问题