Home » Android » android – Not able to UPDATE an item using provider class-Exceptionshub

android – Not able to UPDATE an item using provider class-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

//i used this function in the providers class
  void addItem(String pid,double price,String title){
      _items.update(pid, (newItem)=>CartItem(id: newItem.id, title: newItem.title, price: newItem.price, quantity: newItem.quantity+1));
      print('item added to cart : $pid');  
    } else {
      _items.putIfAbsent(pid,()=>CartItem(id: DateTime.now().toString(), title: title, price: price, quantity: 1));

//and this in one of the screens

 Widget build(BuildContext context) {
    final cart = Provider.of<Cart>(context);
    final list = cart.items;
    return Scaffold(
      appBar: AppBar(title: Text('My Cart'),),
      body: list.isEmpty ? Text('Empty') : ListView.builder(
        // controller: ScrollController(),
        itemCount: list.length,
        itemBuilder:(ctx,i)=> ListTile(
        title: Text(list.values.toList()[i].title),
        subtitle: Text(list.values.toList()[i].price.toString()),
        trailing: IconButton(icon: Icon(Icons.add), onPressed:(){
          cart.addItem(list.values.toList()[i].id, list.values.toList()[i].price, list.values.toList()[i].title);  

I am able to add items from another screen to the cart list using ‘addItem()’, but on calling the same function on the above screen it is always running the else statement from the addItem() function although an item with same id is present.
Edit: _items is initialized and restarting or reloading is not helping.

How to&Answers: