Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to delete an item from a list in Flutter using provider?

I have a list that I am trying to delete a specific item from.

I first tried:

Provider.of<WeekList>(context, listen: false).listOfWeeks.remove(widget.index);

That did not work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

After thinking about it I realized that the Provider is retrieving the list but not actually updating the provider.

So then I decided to use the provider to save retrieve the list and save it to a new list:

List<Week> myList =Provider.of<WeekList>(context, listen: false).listOfWeeks;

I then tried to delete an item at the current position:

myList.remove(widget.index);

I expected the myList to be shortened by one after that last line of code. But I put a print before and after it and they both still say the length is 6…

not sure why its not removign anything from myList. If it worked it should shorten it by one and I planned on then trying to update the provider…. But maybe I am not goign about this correctly.

>Solution :

in your last approach you are changing a "copy" of your list, what you need to do to achieve your goal is to make function inside your state that updates your list and notifies the listeners,
this function to be put inside your ChangeNotifier class:

void updateList(int index)
{
   listOfWeeks.removeAt(widget.index);
   notifyListeners();
}

and you can call it like:

Provider.of<WeekList>(context, listen: false).updateList(index);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading