简体   繁体   English

Flutter:如何检查嵌套列表是否包含值

[英]Flutter: How to Check Nested List is Contains a Value

How to check if List of Maps contains a target value如何检查地图列表是否包含目标值

For example, I have this model Class:例如,我有这个 model Class:

class Data {
  List<Group>? data;

  Data({this.data});
}

class Group {
  int? id;
  List<Weapon>? weaponItems;
  String? groupName;

  Group({
    this.id,
    this.weaponItems,
    this.groupName,
  });
}

class Weapon {
  int? id;
  String? name;

  Weapon({this.id, this.name});
}

From the model that contains nested list:来自包含嵌套列表的 model:

Data => Group => Weapon数据 => 群组 => 武器

or see the variables below to see the details of the structure called mainData或查看下面的变量以查看名为mainData的结构的详细信息

final Data mainData = Data(
  data: [
    Group(
      id: 1,
      groupName: 'Assault Riffle',
      weaponItems: [
        Weapon(id: 1, name: 'Ak47'),
        Weapon(id: 2, name: 'M4'),
      ],
    ),
    Group(
     id: 2,
      groupName: 'SMG',
      weaponItems: [
        Weapon(id: 3, name: 'MP5'),
        Weapon(id: 4, name: 'Dual UZI'),
      ],
    ),
  ],
);

then I have one String variable (target value)然后我有一个字符串变量(目标值)

String myWeapon = 'Dual Uzi';

How to check if mainData contains 'Dual UZI' from myWeapon ?如何检查mainData是否包含来自myWeapon的“Dual UZI”? Is there another way that is more efficient than using a For Loop ?有没有比使用For Loop更有效的另一种方法?

You can use the any function to check if something with a certain quality exists.您可以使用any function 来检查是否存在具有特定质量的内容。 For your example this could be对于您的示例,这可能是

bool hasMyWeapon = mainData.data?.any((group) => group.weaponItems?.any((weapon) => weapon.name == myWeapon) ?? false) ?? false;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM