2

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)
                ),
              }
            ),
          ),
        ),

    );
  }
Leewan
  • 63
  • 3
  • 10

2 Answers2

3

Pass index as your value

  key: ValueKey(index),
Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147
1

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.

Andrey Ozornin
  • 1,129
  • 1
  • 9
  • 24