wick3d
wick3d

Reputation: 1422

How add and remove items from a List using Flutter provider package?

Hello I am trying to add Items to a List _bookMarkedItems.

class Item with ChangeNotifer{
  String id;
  String title;
  bool isBookMarked;
  Item(this.id,this.title,this.isBookMarked);
  void toggleBookMark(){
    isBookMarked=!isBookMarked;
    notifyListneres();
  }
}

Items Class

class Items with ChangeNotifier{
 //recommendedBooks
  List<Item> _recommendedItems=[
  Item('1','Groccery'),
  Item('1','Groccery'),
 ];
  
  //Recommended
  List<Item> _discoverNew=[
  Item('1','Groccery'),
  Item('1','Groccery'),
 ];
 
 List<Item> _bookMarkedItems=[];
//getters
  List<Item> get recommendedItems{
  return [..._recommendedItems];
  }
  List<Item> get discoverNew{
  return [..._discoverNew];
  }
  
  List<Item> get bookMarkedItems{
  _recommendedItems.forEach((item){
    if(item.isBookMarked)
      _bookMarkedItems.add(item);
  });
      _discoverNew.forEach((item){
    if(item.isBookMarked)
      _bookMarkedItems.add(item);
  });
    return [..._bookMarkedItems];
  }
}

When I tap on any Item from _discoverNew or _recommendedItems in the homescreen.dart. //It builds the bookMarkedItems

It ADDS them to the_bookMarkedItems .

But when I go back homescreen and tap on the item again.

//It does not builds the bookMarkedItems and It does NOT update the and not REMOVE item from List_bookMarkedItems. (Here is what I am not understanding). I can add more items from the home page but cannot remove them. In MyApp above myhomepage.dartChangeNotifierProvider(create:(_)=>Items(),.. myitems.dart

  Widget build(BuildContext context) {
    var savedItems= Provider.of<Items>(context).bookMarkedItems;
    print("**************Building savedItem List");
    return Scaffold(
      body: Container(```


  [1]: https://i.sstatic.net/eIS8X.png

Upvotes: 1

Views: 932

Answers (2)

Deepak Pawade
Deepak Pawade

Reputation: 152

make the list of items null within bookMarkedItem function, like this : _bookMarkedItems = [];

Upvotes: 1

try to change isBookMarked = !isBookMarked

Upvotes: 0

Related Questions