1

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.

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

Hi @Jhakiz, thank you for your answer. I forgot to include that I need to remove first to change data and then add back at same location. I was editing my question when you answered. Could you please update your answer for that requirement? Thanks
Which data want you add back? The new object or the existing (where a == 'yellow')??
a new object, but I may need to use data from the original object. So I think I can use the first 2 lines of your code and then do a list.removeAt(index) followed by list.insert(index, {'a': 'brown', 'b': 'white'}). Do you think that is ok or is there a better solution?
@steveny909 those two possibilities give the same result which you're looking for. list[index] = {'a': 'brown', 'b': 'white'}; means remove the object on the index then add the new one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.