Dart maps, how to replace specific key value in a list<map> based on its key id?
792
Solution 1
You can try something like this:
products.where((x) => x["id"] == 48).first["time"] = "2019-10-26 00:00:00.000";
Solution 2
Here is another way how you can do it:
void main() {
List<Map<String, dynamic>> products = [
{'id': 24, 'time': '2019-11-24 00:00:00.000'},
{'id': 36, 'time': '2019-11-23 00:00:00.000'},
{'id': 48, 'time': '2019-11-24 00:00:00.000'},
];
products = products.map((product){
if(product["id"] == 48){
return {...product, 'time': '2019-10-26 00:00:00.000'};
}
return product;
}).toList();
print(products.toString());
}
Author by
Jan
Hello there, I'm code enthusiast working on few projects at the moment
Updated on December 26, 2022Comments
-
Jan over 1 year
void main() { List<Map<String, dynamic>> products = [ {'id': 24, 'time': '2019-11-24 00:00:00.000'}, {'id': 36, 'time': '2019-11-23 00:00:00.000'}, {'id': 48, 'time': '2019-11-24 00:00:00.000'}, ];
In the code above I want to replace 'time' entry '2019-11-24 00:00:00.000' to '2019-10-26 00:00:00.000' for the 'id' 48.
-
Ketan Ramteke over 3 years@Akif, Your flutter answers are really informative.
-
Akif over 3 yearsThank you, @Ketan Ramteke :)
-
Kamlesh almost 3 yearsThanks dear, "return {...product, 'time': '2019-10-26 00:00:00.000'};" worked for me :)
-
Ketan Ramteke almost 3 yearsGlad it helped, happy coding.