Flutter: Keys and when to use them
Flutter keys are the concept that are usually overlooked during Flutter development. Often they are paid attention to when we see some data display inconsistencies. This article contains information about Flutter keys and when when to use them.
In Flutter, keys are used to uniquely identify as well as differentiate between different widgets in the widget tree. Every widget in Flutter accepts a key as parameter, which can be used to identify and track the states of the widget.
Types of Flutter Keys
Key
is an abstract class which is extended by multiple classes which create different types of keys. Each of them accepts different values and serve a different purpose. Few classes which inherit Key are specified below –
1. UniqueKey
UniqueKey
is a special key provided by Flutter which guarantee to be unique across all instances of the app. This key is particularly useful when we knowingly want to create a new instance of the widget every time the it is rebuilt.
2. ValueKey
ValueKey
is a simple key which accepts a single value. This value is then compared with other ValueKey
instances to determine if they are equal. The value is usually and int
or string
and are generally added in a ListView
or GridView
.
3. ObjectKey
ObjectKey
is similar to ValueKey
but instead of taking int
or string
it takes entire object
reference. It is particularly useful when we want the widget to be rebuild when it’s object (model
or entity
) changes.
4. GlobalKey
GlobalKey is used when we want to identify the widget from outside of its parent widget. It provides a way to reference the specific widget from the widget tree. It’s a useful concept in Flutter but it should be used carefully. Overuse can lead to performance issues and make code complicated to understand.
5. LabeledGlobalKey
Same as GlobalKey
but it contains a debug label which is useful in testing.
6. GlobalObjectKey
Same as ObjectKey
but this it is used on Global level, similar to GlobalKey
.
7. LocalKey
It’s an abstract class with extends Key class. This means that it can’t be used directly. All non-global keys extend this class meaning UniqueKey
, ValueKey
and ObjectKey
.
When to use Flutter Keys
Keys are used by Flutter to check the previous state of a widget before rebuilding it. If the old state and new state are same, Flutter won’t rebuild the widget and use the old state. This creates a big performance improvement specially in a List or a Grid which contains multiple widgets of same type.