[英]use the same key for more than one widget in Flutter
Hello StackOverFlow people,你好 StackOverFlow 人,
I am trying to use Keys in Flutter and I am doing well, however, there is something I am really missing, as we know using keys in Flutter is often less usage and rare, and when using keys, it should be unique to that widget and not repeatable, nonetheless, I found I can repeat the same key and use it twice, I can use it more than once, and the code below will explain what I mean.我正在尝试在 Flutter 中使用密钥,我做得很好,但是,我确实缺少一些东西,因为我们知道在 Flutter 中使用密钥通常较少使用且很少见,并且在使用密钥时,它应该是该小部件独有的并且不可重复,尽管如此,我发现我可以重复同一个键并使用它两次,我可以多次使用它,下面的代码将解释我的意思。 Any help will be appreciated.
任何帮助将不胜感激。 Thanks
谢谢
This code does not allow me to use the same key more than once此代码不允许我多次使用同一个密钥
return Scaffold(
appBar: AppBar(title: const Text("Local Key Example"),),
body: Column(
children: [
Text("One", key: ValueKey(1),),
Text("Two", key: ValueKey(2),),
Text("Three", key: ValueKey(1),)
],
),
);
But, this code will allow me to have two widgets with the same key and run with no Errors但是,这段代码将允许我拥有两个具有相同键的小部件并且运行时没有错误
class _LocalKeyPageState extends State<LocalKeyPage> {
List<Widget> myWidget=[
const Text('First', key: ValueKey(1),),
const Text("Second", key: ValueKey(2),),
const Text("Third", key: ValueKey(3),),
const Text("Fourth", key: ValueKey(2),), ];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Local Key Example"),),
body: Column(
children: myWidget.map((e) {
if( e.key== ValueKey(2))
{ return Container(child: e, color: Colors.purple[300], width: 150,height: 50,);}
return Container(child: e,margin: EdgeInsets.all(10), color: Colors.amber,width: 200,height: 100,);
}).toList(),
),
floatingActionButton: FloatingActionButton(
onPressed: (){
setState(() {
myWidget.removeWhere((element)
{return element.key == ValueKey(2);});
});
},
child: Icon(Icons.delete_forever),
),
);
}
}
Keys must be unique amongst the Elements with the same parent.
键在具有相同父元素的元素中必须是唯一的。
Column
, the the children is all the Text
widget.Column
,子级是所有Text
小部件。Text
with Container
.Container
包装Text
。 And now the parent of the Text
is the Container
.Text
的父级是Container
。 But the children of Column
, now is the Container
, which is the Key
is different by default.但是
Column
的孩子,现在是Container
,默认情况下Key
是不同的。 Thats the reason, its run without error.这就是原因,它的运行没有错误。
Container
Container
Column(
children: myWidget.map((e) {
if (e.key == ValueKey(2)) {
return e;
}
this one will throw error like the first example.这个会像第一个例子一样抛出错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.