Flutter中如何对比不同长度列表并判断新闻机构是否已关注
解决思路与代码修改
你的核心问题是没有对两个列表的关联关系做实际判断,只是把following变量固定设为false,所以按钮状态不会变化。下面是具体的解决方法:
第一步:预处理已关注的新闻ID(提升性能)
先把following列表里所有的newsid提取出来存成一个集合,集合的查询效率远高于遍历列表:
// 在获取到newsAgency和following数据后执行 Set<int> followedNewsIds = following.map((item) => item['newsid'] as int).toSet();
第二步:修改ListView代码,实现状态判断
在itemBuilder里,用当前新闻机构的ID去集合里查询,就能得到是否已关注的状态:
ListView.builder( itemCount: newsAgency.length, itemBuilder: (BuildContext context, int index) { // 获取当前新闻机构的ID,注意类型转换 int currentNewsId = newsAgency[index]['id'] as int; // 判断是否已关注 bool isFollowing = followedNewsIds.contains(currentNewsId); return Card( elevation: 10.0, child: Row( children: [ Text(newsAgency[index]['name']), const SizedBox(width: 12), // 添加间距优化布局 isFollowing ? TextButton( onPressed: () { // 取消关注逻辑: // 1. 调用接口更新后端数据 // 2. 更新本地following列表和followedNewsIds集合 // 3. 调用setState刷新UI }, child: const Text('取消关注'), ) : TextButton( onPressed: () { // 关注逻辑: // 1. 调用接口更新后端数据 // 2. 更新本地following列表和followedNewsIds集合 // 3. 调用setState刷新UI }, child: const Text('关注'), ), ], ), ); }, )
关键说明
- 为什么用集合?如果
following列表数据量大,每次遍历判断会浪费性能,集合的contains方法是O(1)的查询效率,比遍历列表的O(n)高效很多。 - 类型转换必须注意:从JSON取出的
id和newsid是dynamic类型,必须转成int才能正确匹配。 - 操作按钮后要更新本地数据并调用
setState,这样UI才会实时刷新状态。
内容的提问来源于stack exchange,提问作者Texv
相关产品推荐
相关产品推荐

