How can I update the list after changing an Item status? (Flutter and Provider) How can I update the list after changing an Item status? (Flutter and Provider) dart dart

How can I update the list after changing an Item status? (Flutter and Provider)


To be honest the way Provider works is by propagating the data down the widget tree, from parent to children, but you want the child (Item) to notify the parent to change (Collection) and that would make both parent and children codependent (and would lead to some spaguetti code later). If every change to the favourite is going to update the list then it would be better just to keep the whole logic in Collection and keep the Item class as a simpel model

class Collection with ChangeNotifier {  List<Items> _items = [    Items(name: "a", favourite: true),    Items(name: "b", favourite: true),    Items(name: "c", favourite: true),  ];  List<Items> get favItems =>      [..._items].where((element) => element.favourite == true).toList();  toggleFavourite(Item item) {    int index = _items.indexWhere((element) => element.name == item.name);    _items[index].favourite = !_items[index].favourite;    notifyListeners();  }}class Items { //simple Model class  String name;  bool favourite;  Items({this.name, this.favourite});}class MyHomePage extends StatelessWidget {  @override  Widget build(BuildContext context) {    final _list = context.select((Collection list) => list.favItems);     //to update only if list is different    return Scaffold(      appBar: AppBar(        title: Text("Test"),      ),      body: Container(        child: ListView.builder(          itemCount: _list.length,          itemBuilder: (_, index) => CardWidget(_list[index])        ),      ),    );  }}class CardWidget extends StatelessWidget {  final Item _item;  CardWidget(this._item);  @override  Widget build(BuildContext context) {    return Card(      child: Row(        children: <Widget>[          Text(_item.name),          IconButton(              icon:                  _item.favourite ? Icon(Icons.star) : Icon(Icons.star_border),              onPressed: () {                Provider.of<Collection>(context, listen: false).toggleFavourite(_item);              })        ],      ),    );  }}


Is the problem that the list isn't visually updating altough the item is removed from the list? Try using:

Container(    key: UniqueKey(),    child: CardWidget())

I don't know why it works but this worked for me when I had this problem.


Try use the 'setState()' method, that rebuild your screen and You should see the changes