flutter 如何比较2个不同长度的阵列并寻找匹配值-扑动

xytpbqjk  于 2023-01-09  发布在  Flutter
关注(0)|答案(2)|浏览(146)

我不确定我的策略或逻辑是否正确,但我有2个列表来自2个不同的jsondata mysql查询,假设它们看起来像这样:

List newsAgency = [{id: 1, name: 9news, image: x} 
                   {id: 2, name: abcnews, image: y} 
                   {id: 3, name: bbcnews, image:z}];

List following = [{userid: 41, username: x, newsid: 2}
                  {userid: 41, username: x newsid: 3}];

我想看看newsAgency中的id是否与下面列表中的newsid匹配,并相应地返回true或false。
这个想法是说,我正在以下2新闻机构的3,所以我的目标是显示按钮,以遵循或取消遵循的基础上的结果。
我尝试了这篇文章how can I find a list contains in any element another list in flutter?中建议的所有方法,但都没有成功。
这是我的代码示例:

Listview.builder(
  itemCount: newsAgency.length,
  itemBuilder: (BuildContext context, int index) {
    bool following = false;
    return Card(
        elevation: 10.0,
        child: Row(
            children: [
                Text(newsAgency[index]['name'],
                following 
                ? TextButton(onPressed: () {//unfollow function},
                            child: const Text('unfollow')),
                : TextButton(onPressed: () {//follow function},
                            child: const Text('follow')),
                ]));});

任何帮助都将不胜感激

t5zmwmid

t5zmwmid1#

在类中添加此方法,它将负责搜索哪些项在后面,哪些项不在后面,并根据它返回一个bool:

bool checkIsFollowing(Map<String, dynamic> current) {
    for(int index = 0; index < following.length; index+=1) {
      if(current["id"] == following[index]["newsid"]) {
        return true;
      }
    }
    return false;
  }

现在,在您的ListViewitemBuilder中,替换以下内容:

bool following = false;

用这个

final currentNewsAgency = newsAgency[index];
 bool following = checkIsFollowing(currentNewsAgency);

following将根据当前代理的id是否存在于以下列表中的某个项目中而为true或false。

7kqas0il

7kqas0il2#

使用contains()方法检查列表中是否包含您想要匹配的值,例如:-
following.contains(newsAgency[index]['name'].toString())//如果值匹配则为真。

相关问题