Home > Net >  Change a key in a Map
Change a key in a Map

Time:10-23

I want to update a key from "new" to "1". How can I do this ?

Old One:

Map<String, String> titleTextFieldList = {"new":"title"};

What I want:

{"1":"title"}

CodePudding user response:

as the @rosh-dev state.

Map<String, String> titleTextFieldList = {"new":"title"};

Map<String, String> titleTextFieldList2 ={"1": titleTextFieldList['new']}
print('$titleTextFieldList2');

CodePudding user response:

Have a look. You can do it create a new map and checking the key if it matches then replacing it with another key.

void main() {
  Map<String, String> titleTextFieldList = {"new": "title", "test": "test"};
  Map<String, String> newMap = {};

  titleTextFieldList.forEach((i, value) {
    if (i == "new") {
      newMap["1"] = value;
    } else {
      newMap.addAll({"$i": "$value"});
    }
  });

  print(newMap); //{1: title, test: test}
}

CodePudding user response:

void main() { 
  Map<String, String> titleTextFieldList = {"new": "title","b":"kkk"};
  Map<String, String> newMap = {};

  int i = 1; 
  titleTextFieldList.keys.toList().forEach((key) { 
    newMap.addAll( {"${key=='new'?'1':key}": titleTextFieldList[key]}); i  ; });

  print(titleTextFieldList); 
  print(newMap);
}

output is:

{"new": "title", "b": "kkk"}
{"1": "title", "b": "kkk"}
  • Related