trizin
trizin

Reputation: 343

Dart check if array of maps contains a specific map

I want to check if an array of maps contains a specific map.

void main() {
  List<Map> mapArray = [{"a":1,"b":1}];
  print(mapArray.contains({"a":1,"b":1})); // prints false
}

Even though the mapArray array contains that {"a":1,"b":1} map, mapArray.contains function will return false. I've found a solution by converting the maps into strings and checking if the array contains that string.

print(mapArray.map((x)=>x.toString()).contains({"a":1,"b":1}.toString())); // prints true

However, this doesn't look like the best solution. Please let me know if there is a better workaround for this issue.

Upvotes: 0

Views: 1388

Answers (1)

Amirhossein Shahbazi
Amirhossein Shahbazi

Reputation: 1111

You can use the equals method of DeepCollectionEquality:

import 'package:collection/collection.dart';

void main() {
  List<Map> mapArray = [{"a":1,"b":1}, {"c":25,"d":99}];
  print(mapArray.any((element) => DeepCollectionEquality().equals(element, {"a":1,"b":1})));
}

Upvotes: 5

Related Questions