What are keys and their role in Flutter?

widget

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.

Need of keys

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.

Syntax

Widget(Key: TypeOfKey(optional_paramter))
  • A widget is any widget whose state we want to store in the key.
  • The 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.

Types of keys

There are four types of keys in Flutter, which are as follows:

  • Value key: It stores the alphanumeric value of the widget.
  • Object key: It stores complex objects in which multiple objects have the same values, such as date of birth or name. It usually would be a custom class.
  • Unique key: It stores every widget state as unique. It is easy to identify them when we need to recall them.
  • Global key: It allows developers to access the data of one widget inside another in your application. It can help the developers but can also destroy the state management. It is a very controversial key as better state management options are available. It can be helpful in form validation situations where we need to validate some common data.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved