从Flutter列表中删除项目时遇到问题。

huangapple go评论56阅读模式
英文:

trouble removing an item from a list Flutter

问题

我有一个在我的应用中的切换按钮,当按下它时,它会向列表中添加一个项目。再次按下它时,它会从列表中删除该项目。按钮是有效的,当第一次按下它时,它会添加项目,但再次按下它时,它不会删除项目。

以下是根据按钮的布尔值来添加/删除项目的Inkwell中的代码。

if (context.read<MyProvider>().SelectList[0].buttonBool == false) {
  context.read<MyProvider>().InfoList.add(Entries(
    text: 'Hello World',
    logID: LogID.entry1,
  ));
} else if (context.read<MyProvider>().SelectList[0].buttonBool == true) {
  context.read<MyProvider>().MissionInfoList.remove(LogID.entry1);
}

如你所见,当按钮返回false时,它会将一个Entries添加到InfoList中,该Entries具有文本和LogID(以便在需要时轻松找到并删除它)。

但是,当按钮返回true时,它没有基于对象(LogID)从列表中删除该条目。

我是新手使用列表,很想了解我在这里做错了什么。

非常感谢,任何帮助将不胜感激。

英文:

I have a Toggle button in my app that when it is pressed it adds an item to a list. and when it is pressed again, it removes the item from the list. the button is working and when you press it for the first time, it ads the item but when it is pressed again, it doesn't remove it.

here is the code from the inkwell to add/remove the item based on the buttons bool.

if (context.read&lt;MyProvider&gt;().SelectList[0].buttonBool == false) {
                      context.read&lt;MyProvider&gt;().InfoList.add(Entries(
                          text: &#39;Hello World&#39;,
                          logID: LogID.entry1));
                    } else if (context.read&lt;MyProvider&gt;().SelectList[0].buttonBool == true) {
                      context.read&lt;MyProvider&gt;().MissionInfoList.remove(LogID.entry1);
                    }

As you can see, when the button returns false, It adds an Entries to the InfoList which has a Text and a LogID (so it can be found easily if i want to remove it)

but when the button returns true, it is not removing the entry in the list based off an object(the LogID)

I'm new to using lists and am keen to understand what I'm doing wrong here.

thanks so much and any help would be greatly appreciated

答案1

得分: 1

你需要筛选ID以找到要删除的对象:

context.read<MyProvider>().MissionInfoList.removeWhere((element) => element.logID == LogID.entry1);
英文:

You have to filter for the id to find the object you want to delete:

context.read&lt;MyProvider&gt;().MissionInfoList.removeWhere((element) =&gt; element.logID == LogID.entry1);

huangapple
  • 本文由 发表于 2023年7月20日 17:33:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76728531.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定