Dart 从列表中删除索引自定义小部件<;Widget>;飘飘然
我最初在列中有一个空的小部件列表。现在,在其他小部件上单击“我正在将新的自定义小部件添加到\u contactItems中”Dart 从列表中删除索引自定义小部件<;Widget>;飘飘然,dart,flutter,flutter-sliver,dart-2,Dart,Flutter,Flutter Sliver,Dart 2,我最初在列中有一个空的小部件列表。现在,在其他小部件上单击“我正在将新的自定义小部件添加到\u contactItems中” Column( children: _contactItems, ) List<Widget> _contactItems = new List<CustomWidget>(); _contactItems.add(newCustomWidget(value)); 也试过了 _contactItems.rem
Column(
children: _contactItems,
)
List<Widget> _contactItems = new List<CustomWidget>();
_contactItems.add(newCustomWidget(value));
也试过了
_contactItems.removeWhere((item) {
return item.key == _contactItems[index].key;
});
尝试以下操作(假设您的列小部件键具有此格式):
如果这不能解决您的问题,我们可能需要更多信息。如果您想要操作ListView或GridView,则为List/GridView的每个子小部件分配一个键非常重要 简而言之,flatter只按类型而不是状态比较小部件。因此,当列表/网格视图中表示的列表的状态发生变化时,Flatter不知道应该删除哪些子项,因为它们的类型仍然相同,并且会检出。Flatter唯一关注的问题是项目的数量,这就是为什么它只删除列表/网格视图中的最后一个小部件 因此,如果您想在flatter中操作列表,请为每个子级的顶级小部件分配一个键。有关更详细的说明,请参阅 这可以通过添加
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')
),
);
}),
);
问题是什么?它总是删除最后一个小部件。索引没有问题。对列中的每个子项使用removeAtgive UniqueKey可能有问题。我尝试使用key:key(“index_$index”),并与_contactItems进行比较。removeWhere((item){return item.key==_contactItems[index].key;});哇:太好了!我不知道为什么我们需要像那样比较键我也有同样的问题,你是如何给列中的项目一个唯一的键的?
setState(() {
this._contactItems.removeWhere((contact) => contact.key == Key("index_$index"));
});
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')
),
);
}),
);