Shahzad Umar Baig
Shahzad Umar Baig

Reputation: 172

Map<String, dynamic> values not updating in class in flutter/Dart

I have created a class called Cart in a different dart file

class Cart {
  String title;
  double price;
  int quantity;
  double total;

  Cart({this.title, this.total, this.price, this.quantity});
  Map<String, dynamic> cartListItems = {
    "Bread": {
      "quantity": 1,
      "price": 60.0,
      "total": 60.0,
    },
  };
}

This Map is used on cart Screen to fetch data against the keys, it is working fine but the problem is when I try to update the quantity it doesn't update. the code below is a dropdown onChanged callback, drop down has value from 1 to 6 and it is assigning value to local variable perfectly it is just that the value in Map doesn't update. I have tried using the cartListItems.update(key, (value)) method as well, not working.

 onChanged: (value) {
    setState(() {
       Cart().cartListItems[cartItemNames[0]]["quantity"] = value + 1;

       Cart().cartListItems[cartItemNames[0]]["total"] =
                  Cart().cartListItems[cartItemNames[0]]["quantity"] *
                  Cart().cartListItems[cartItemNames[0]]["price"];
    });
},

Upvotes: 0

Views: 2463

Answers (1)

Shahzad Umar Baig
Shahzad Umar Baig

Reputation: 172

I have found solution to my own question. There are two things you can do, depends on the scenario in my case I wanted to access the same map across all the screen so I moved the Map out of my class to global into the same file.

Map<String, dynamic> cartListItems = {};

class Cart {
  String title;
  double price;
  int quantity;
  double total;

  Cart({this.title, this.total, this.price, this.quantity});
}

Then in the screen class worked if I don't use the update method to update the file, the same code worked

onChanged: (value) {
    setState(() {
       cartListItems[cartItemNames[index]]["quantity"] = value + 1;

       cartListItems[cartItemNames[index]]["total"] =
                  cartListItems[cartItemNames[index]]["quantity"] *
                  cartListItems[cartItemNames[index]]["price"];
    });
},

I do not know if this is a correct approach but it worked for me, in second case if you don't want to access the values across the app. You can simply move the Map to Screen State class, you can keep it empty their and update it accordingly.

Anyone can put a better answer so I can know if this is a correct approach.

Upvotes: 1

Related Questions