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());
    }
Share:
792
Jan
Author by

Jan

Hello there, I'm code enthusiast working on few projects at the moment

Updated on December 26, 2022

Comments

  • Jan
    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
    Ketan Ramteke over 3 years
    @Akif, Your flutter answers are really informative.
  • Akif
    Akif over 3 years
    Thank you, @Ketan Ramteke :)
  • Kamlesh
    Kamlesh almost 3 years
    Thanks dear, "return {...product, 'time': '2019-10-26 00:00:00.000'};" worked for me :)
  • Ketan Ramteke
    Ketan Ramteke almost 3 years
    Glad it helped, happy coding.