This post will teach you to update the Map value in Dart or Flutter. You may need to update the value of the map in many conditions and instances like when you have new values for any map element. See the example below to update the hashMap value in different ways:
Map values = {
"a":"Elephant",
"b":"Horse",
"c":"Lion",
"d":"Deer"
};
values["c"] = "Cow";
print(values);
//output: {a: Elephant, b: Horse, c: Cow, d: Deer}
Here, the Map with key "c" will be updated with the new value "Cow".
Map values = {
"a":"Elephant",
"b":"Horse",
"c":"Lion",
"d":"Deer"
};
values.forEach((key, value) {
if(value == "Lion"){
values[key] = "Goat";
}
});
print(values);
//Output: {a: Elephant, b: Horse, c: Goat, d: Deer}
Here, the map with the value "Lion" will have a new value of "Goat".
Map values = {
"a":"Elephant",
"b":"Horse",
"c":"Lion",
"d":"Deer"
};
values.update("c", (value) => "Mouse");
print(values);
//output: {a: Elephant, b: Horse, c: Mouse, d: Deer}
Here, the value of the map with key "c" will have a new value.
Map values = {
"a":"Elephant",
"b":"Horse",
"c":"Lion",
"d":"Deer"
};
values.updateAll((key, value){
if(key == "c"){
return "Rat";
}else{
return value;
}
//you can also use the value to compare
});
print(values);
//output: {a: Elephant, b: Horse, c: Rat, d: Deer}
If you don't know the key, you can use the value to compare and return the new value if matched.
Map values = {
"a":"Elephant",
"b":"Horse",
"c":"Lion",
"d":"Deer"
};
values.updateAll((key, value) => "Animal");
print(values);
//output: {a: Animal, b: Animal, c: Animal, d: Animal}
Here, all the Map values will be replaced with the new value "Animal".
In this way, you can update the value of Map in Dart or Flutter.
Please Wait...
No any Comments on this Article