![](/img/trans.png)
[英]Prevent widget from being rebuilt more than one time at the same time in Flutter
[英]use the same key for more than one widget in Flutter
你好 StackOverFlow 人,
我正在尝试在 Flutter 中使用密钥,我做得很好,但是,我确实缺少一些东西,因为我们知道在 Flutter 中使用密钥通常较少使用且很少见,并且在使用密钥时,它应该是该小部件独有的并且不可重复,尽管如此,我发现我可以重复同一个键并使用它两次,我可以多次使用它,下面的代码将解释我的意思。 任何帮助将不胜感激。 谢谢
此代码不允许我多次使用同一个密钥
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),)
],
),
);
但是,这段代码将允许我拥有两个具有相同键的小部件并且运行时没有错误
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),
),
);
}
}
键在具有相同父元素的元素中必须是唯一的。
Column
,子级是所有Text
小部件。Container
包装Text
。 现在Text
的父级是Container
。 但是Column
的孩子,现在是Container
,默认情况下Key
是不同的。 这就是原因,它的运行没有错误。
Container
Column(
children: myWidget.map((e) {
if (e.key == ValueKey(2)) {
return e;
}
这个会像第一个例子一样抛出错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.