Home > Back-end >  How to delete an item from a list in Flutter using provider?
How to delete an item from a list in Flutter using provider?

Time:04-03

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.

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.

CodePudding user response:

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);

CodePudding user response:

If you're removing by index, you need to use removeAt.

  • Related