Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: How to Check Nested List is Contains a Value

Tags:

flutter

dart

How to check if List of Maps contains a target value

For example, I have this 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:

Data => Group => Weapon

or see the variables below to see the details of the structure called 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? Is there another way that is more efficient than using a For Loop?

like image 939
Septian Dika Avatar asked Feb 25 '26 15:02

Septian Dika


1 Answers

You can use the any function to check if something with a certain quality exists. For your example this could be

bool hasMyWeapon = mainData.data?.any((group) => group.weaponItems?.any((weapon) => weapon.name == myWeapon) ?? false) ?? false;
like image 55
Ivo Beckers Avatar answered Feb 28 '26 08:02

Ivo Beckers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!