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

Exception or error:
//i used this function in the providers class
  void addItem(String pid,double price,String title){
    if(_items.containsKey(pid)){
      _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));
    }
    notifyListeners();
  }

//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()),
        leading:Text(list.values.toList()[i].quantity.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 solve:

Leave a Reply

Your email address will not be published. Required fields are marked *