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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With