Reputation: 63
When I run this code I'm getting an error: Multiple widgets used the same GlobalKey.
So I can fix this issue.
How I can pass dynamically keys to my listview.Builder. is it possible to pass?. Here is simplified version my code:
GlobalKey<AutoCompleteTextFieldState<String>> key0 = new GlobalKey();
@override
Widget build(BuildContext context) {
return M Scaffold(
appBar: appBar,
body: SingleChildScrollView(
child: Container(
child: ListView.builder(
itemCount: 3,
itemBuilder: (context, index) {
return SimpleAutoCompleteTextField(
key: key0,
suggestions: suggestions,
textChanged: (text) => print(text),
clearOnSubmit: false,
textSubmitted: (text) => print(text)
),
}
),
),
),
);
}
Upvotes: 2
Views: 7137
Reputation: 645
Make Sure the FormBuilder key that you are using should be used single time only into the entire screen.
Into your case please check the key0, how many times you have used in same screen.
Upvotes: 0
Reputation: 1158
GlobalKey must be unique across the entire application.
You cannot simultaneously include two widgets in the tree with the same global key. Attempting to do so will assert at runtime.
It means that multiple elements can't use the same key. Here's a short video about keys in Flutter and not that short article about using keys, including GlobalKey
's.
What you should do in this case is to derive keys of each element from their uniquely defining features such as content or some ID.
Things to note:
Key('AAA') == Key('AAA'); // true
it means that you don't have to create Key
objects outside of your build function and can go with just:
return SimpleAutoCompleteTextField(
key: Key(itemId),
or even rather ValueKey(itemData)
in your case: ValueKey.
GlobalKey
's are relatively expensive and if you don't explicitly need to move them from one place of the app to another, prefer regular Key
.
Don't derive keys from indices. It's considered a bad practice because it will lead to misbehavior when you try to reorder existing widgets in the same subtree.
Upvotes: 1