Mark
Mark

Reputation: 3849

Is it possible to remove data from a map based on a key-value pair in dart/flutter?

I have a map that goes like this

[
  {
   pid: 8876,
   name: Alex
  },
  {
   pid: 5228,
   name: John
  },
  {
   pid: 9762,
   name: Fred
  }
]

And I need to delete an entire entry based on the pid, so for example, if pid == 5228 then it would delete the entire corresponding entry and the result would be:

[
  {
   pid: 8876,
   name: Alex
  },
  {
   pid: 9762,
   name: Fred
  }
]

Upvotes: 1

Views: 782

Answers (2)

Roaa
Roaa

Reputation: 1440

Try this out, it allows you to have more control over what you need to filter out from your list

List<Map<String, dynamic>> list1 = [
  {
    'pid': 8876,
    'name': 'Alex',
  },
  {
    'pid': 5228,
    'name': 'John',
  },
  {
    'pid': 9762,
    'name': 'Fred',
  }
];

void main() {
  List<Map<String, dynamic>> list2 = [];
  for (Map<String, dynamic> listItem in list1) {
    if(listItem['pid'] != 5228) {
      list2.add(listItem);
    }
  }
  print(list2);
}

Upvotes: 0

vladzaba
vladzaba

Reputation: 1402

You can use removeWhere method.

For example: map.removeWhere((pid, name) => pid == 5228);

Upvotes: 4

Related Questions