Leewan
Leewan

Reputation: 63

Flutter: Multiple widgets used the same GlobalKey

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

Answers (3)

Abhay
Abhay

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

Andrey Ozornin
Andrey Ozornin

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:

    1.
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.

  1. 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.

  2. 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

Jitesh Mohite
Jitesh Mohite

Reputation: 34210

Pass index as your value

  key: ValueKey(index),

Upvotes: 3

Related Questions