0

I want to Update a array inside a map

Map<int, List<String>> testtable = {
    1: ['a', 'b', 'c', 'e'],
    2: ['f', 'g', 'h', 'j'],
  };

I want to Update e => d in array which has key = 1 ,

I Have Tried this testtable.update(1, (list[3]) => d); but doesn't work

4 Answers 4

1

update expect the new value as the parameter, so you have to return the whole list.

testtable.update(1, (list) {
    list[3] = 'd';
    return list;
});
Sign up to request clarification or add additional context in comments.

Comments

1

You can do it this way:

testtable.update(
  1,
  (value) {
    value[3] = 'd';
    return value;
  },
);

Comments

1

Another option:

void main() {
  Map<int, List<String>> testtable = {
    1: ['a', 'b', 'c', 'e'],
    2: ['f', 'g', 'h', 'j'],
  };
  
  print (testtable);
  
  testtable[1][3]='d';
  print (testtable);
}

3 Comments

this doesn't work,, it only works with List<List<String>> ,not map
Why shouldn't it work? It is valid and works. One way to read values from a Map is uisng the [] operator. In this example your Map's keys are integers so testtable[1] is totally correct and returns the value of key 1.
I tested it in dartpad before posting, and it worked just fine.
1

Update nested Map

 Map<String, Map> selectedTimes = {
    "monday": {"open": "7:30 AM", "close": "10:30 AM"},
    "tuesday": {"open": "7:30 AM", "close": "10:30 AM"},
    "wednesday": {"open": "7:30 AM", "close": "10:30 AM"},
    "thursday": {"open": "7:30 AM", "close": "10:30 AM"},
    "friday": {"open": "7:30 AM", "close": "10:30 AM"},
    "saturday": {"open": "7:30 AM", "close": "10:30 AM"},
    "sunday": {"open": "7:30 AM", "close": "10:30 AM"}
  };


selectedTimes.update(day, (list) {
  list.update(
      time, (value) => selectedTimeRTL!.format(context).toString());
  return list;
})

Comments

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.