In Flutter, keys store the widget’s state when the device moves from one branch to another in the widget tree.
Keys can be found in almost every widget as named parameters. It is useful when we need to store the widget’s state having the same type of data. It's used with a stateful widget where states change.
We can add keys almost everywhere in our code, but using unnecessary memory resources is not good practice.
Flutter builds not only a widget tree of the application but also an element tree. The element tree only has the information of the widgets present in the widget tree and references to its children’s widgets. If the element tree is not changed, then, Flutter will not call its build function of a stateful widget, and we can face UI problems in our applications.
To solve this problem, we can use keys. Keys are attached to the widget elements, making them distinguishable in the element tree even if they have the same widgets.
We use keys where multiple widgets of the same type are present at the same level of the widget tree. We declare the key at the top of the branch of the widget tree whose states need to preserve.
Widget(Key: TypeOfKey(optional_paramter))
widget
is any widget whose state we want to store in the key.key
is the named parameter.TypeOfKey()
will be replaced by the name of the type of keys we want to use, i.e., Value, Object, Unique, Global keys. Some keys take variable data they want to store, such as Value and Object keys.There are four types of keys in Flutter, which are as follows:
Free Resources