Home > Blockchain >  how to update a list used as a value for a map in dart
how to update a list used as a value for a map in dart

Time:12-08

I have been trying to update a Map<String, List> sender like I would a normal map, and I haven't had any luck. I looked at this question but trying to add a [0] to mark the index doesn't work. I keep getting a Script error so when the list isn't even being displayed in my UI, I can't trace why. I want sender to be {"Header" : [content]} then to_repo is called again {"Header" : [content, content]}

void to_repo(content) {
    if (!sender.containsKey('Header')) {
  sender['Header'][0] = content;
}
  else if (sender.containsKey('Header')) {  sender.update(
       "Header",
         (value) => value.add(content.toString()),
       
      // ifAbsent: () => content.toString(),
       );
                                          }
    

CodePudding user response:

Instead of

sender['Header'][0] = content;

you can do

sender['Header'] = [content];

EDIT:

I believe you could also rewrite the function to this:

void to_repo(content) {
  sender['Header'] = (sender['Header'] ?? [])..add(content);
}
  • Related