Hello StackOverFlow people,
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. 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),
),
);
}
}
CodePudding user response:
Keys must be unique amongst the Elements with the same parent.
- in your first example, the parent is
Column
, the the children is all theText
widget.
- in your second example, you wrap the
Text
withContainer
. And now the parent of theText
is theContainer
.
But the children of Column
, now is the Container
, which is the Key
is different by default. Thats the reason, its run without error.
- if you remove the
Container
Column(
children: myWidget.map((e) {
if (e.key == ValueKey(2)) {
return e;
}
this one will throw error like the first example.