AskYous
AskYous

Reputation: 4720

Why is there "key" a parameter of some constructors and what is it for?

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?

Upvotes: 1

Views: 85

Answers (1)

boformer
boformer

Reputation: 30103

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.

Upvotes: 2

Related Questions