Subair K
Subair K

Reputation: 1880

Why .contains not checking in List<Map>?

function:

var mapList = [
  {"id": "1", "name": "zein"},
  {"id": "2", "name": "john"},
];

print(mapList.contains({"id": "1", "name": "zein"}));

Result: false

The list actually contains the value. Why is it still false?

Upvotes: 2

Views: 846

Answers (2)

OMi Shah
OMi Shah

Reputation: 6186

As suggested by @enzo, you can use the mapEquals to compare two map objects as:

import 'package:flutter/foundation.dart';

void main() {
  var mapList = [
    {"id": "1", "name": "zein"},
    {"id": "2", "name": "john"}
  ];

  var toCheck = {"id": "1", "name": "zein"};

  print(mapList.any((e) => mapEquals(e, toCheck))); // true
  
}

Alternatively, you can iterate the list and check as:

mapList.forEach((e) {
  print(mapEquals(e, toCheck));
});

Upvotes: 2

Abbas Jafari
Abbas Jafari

Reputation: 1643

Just try these lines of code:

List<Map<String, dynamic>> mapList = [
  {"id": "1", "name": "zein"},
  {"id": "2", "name": "john"},
];

mapList.forEach((element) {print(element.keys.contains("id"));});

mapList.forEach((element) {print(element.values.contains("zein"));});

It doesn't work because you need to do it separately.

Upvotes: 2

Related Questions