3

我最初在 Column 中有空的 Widget 列表。现在在其他小部件上单击我在 _contactItems 添加新的自定义小部件

   Column(
      children: _contactItems,
    )

 List<Widget> _contactItems = new List<CustomWidget>();



 _contactItems.add(newCustomWidget(value));

现在假设我有 6 条记录(列中有 6 个自定义小部件)。我正在尝试删除索引明智的记录(例如。我正在删除第 3 条记录,然后是第 1 条记录。列小部件(动态小部件)应更新为 _contactItems 更新setState()

现在在CustomWidget上单击我正在从 Column 中删除该特定的 CustomWidget 。

setState(() {
          _contactItems.removeAt(index);
        });

也试过了

_contactItems.removeWhere((item) {
            return item.key == _contactItems[index].key;
          });
4

2 回答 2

5

试试这个(假设您的 Column 小部件键具有这种格式):

setState(() {
  this._contactItems.removeWhere((contact) => contact.key == Key("index_$index"));
});

如果这不能解决您的问题,也许我们需要更多信息。

于 2019-01-22T15:35:21.050 回答
0

If you want to manipulate a ListView or GridView it is important that you assign a Key to each child Widget of the List/GridView

In short Flutter compares widgets only by Type and not state. Thus when the state is changed of the List represented in the List/GridView, Flutter doesn't know which children should be removed as their Types are still the same and checks out. The only issue Flutter picks up is the number of items, which is why it only removes the last widget in the List/GridView.

Therefore, if you want to manipulate lists in Flutter, assign a Key to the top level widget of each child. A more detailed explanation is available in this article.

This can be achieved be adding

   return GridView.count(
  shrinkWrap: true,
  crossAxisCount: 2,
  crossAxisSpacing: 5.0,
  mainAxisSpacing: 5.0,
  children: List.generate(urls.length, (index) {
    //generating tiles with from list
    return   GestureDetector(
        key: UniqueKey(), //This made all the difference for me
        onTap: () => {
          setState(() {
            currentUrls.removeAt(index); // deletes the item from the gridView
          }) 

        },
        child: FadeInImage( // A custom widget I made to display an Image from 
            image:  NetworkImage(urls[index]),
            placeholder: AssetImage('assets/error_loading.png') 
            ),

    );
  }),

);
于 2020-10-17T21:23:42.293 回答