steveny909
steveny909

Reputation: 105

how to replace object in List<Map> at same index location in Flutter

So lets say I have a list of objects like this:

List<Map<String, dynamic>> list = [{'a': 'red', 'b': 'blue'}, {'a': 'yellow', 'b': 'orange'}, {'a': 'green', 'b': 'purple'}];

Assuming each a and b value is unique, how would I find the object where a === yellow and replace that object with a new object like {'a': 'brown', 'b': 'white'} at the same index location in the list of the original object?

EDIT I forgot to mention, I need to remove the object first to manipulate the data and then add it back at same location.

Upvotes: 1

Views: 3392

Answers (1)

Jhakiz
Jhakiz

Reputation: 1609

Try this:

  var item = list.firstWhere((i) => i["a"] == 'yellow'); // getting the item
  var index = list.indexOf(item); // Item index
  list[index] = {'a': 'brown', 'b': 'white'}; // replace item at the index

Upvotes: 2

Related Questions