1

I keep seeing this in a lot of Flutter code but I have no idea what it does or what the point of it is:

TextField(
    style: Theme.of(context).textTheme.display1,
    key: _inputKey, // <-------------- what is this?
AskYous
  • 3,740
  • 5
  • 40
  • 69
  • 5
    Possible duplicate of [What are Keys in the Stateless widgets class?](https://stackoverflow.com/questions/50080860/what-are-keys-in-the-stateless-widgets-class) – Rémi Rousselet Aug 17 '18 at 17:42

1 Answers1

2

Using a Key, you can tell Flutter that a widget is the same (or not the same) after a rebuild. That's especially important when those widgets hold internal state (e.g. a running animation).

When you add or remove widgets from a list (Column or ListView) on a rebuild, Flutter does not know which widgets were added, which ones were moved and which ones were removed. Such a use case is described in the question linked by Rémi.

A GlobalKey is a special kind of key that allows you to access the State and RenderObject (and size) of the widget.

The AnimatedSwitcher which allows you to switch out a widget with an animation often requires keyed children to signalize if an animation should occur, or if the widget is the same after a rebuild.

boformer
  • 24,561
  • 8
  • 72
  • 58