如何使用提供商的扑波列表中删除项目?

发布于 2025-01-18 12:39:53 字数 583 浏览 3 评论 0原文

我有一个列表,我试图从中删除特定项目。

我第一次尝试:

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

那不起作用。

经过思考,我意识到提供者正在检索列表,但实际上并没有更新提供者。

因此,我决定使用提供程序来保存检索列表并将其保存到新列表中:

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

然后我尝试删除当前位置的项目:

myList.remove(widget.index);

我希望 myList 在最后一行代码之后缩短一个。但我在它之前和之后都打印了一个内容,他们仍然说长度是 6...

不知道为什么它不从 myList 中删除任何内容。如果它有效,它应该将其缩短一,我计划然后尝试更新提供程序......但也许我没有正确地解决这个问题。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

反话 2025-01-25 12:39:53

在您的最后一种方法中,您正在更改列表的“副本”,为了实现您的目标,您需要做的是在您的状态内创建函数来更新您的列表并通知听众,
将此函数放入您的 ChangeNotifier 类中:

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

您可以这样调用它:

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

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);
榆西 2025-01-25 12:39:53

如果您通过索引删除,则需要使用removeat。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文