Flutter Keys: The Why, The When, and How to Go About Them

Know the types of keys and how to use them

Dedan Ndungu
Better Programming
Published in
3 min readFeb 27, 2022

--

Photo by Angela Merenkova on Unsplash

Flutter Keys is a concept that is often overlooked until you start experiencing misbehaviors in your data display. This article contains short reference notes about keys that I use to implement this concept and fix those weird bugs.

When?

Keys are oftenly used when we are modifying a collection of widgets of the same type that hold some state. Most times we apply them to Widget children such as Listview or Stateful widgets whose data keeps changing.

Why?

The key concept is flutters' way to keep a reference to state and access the state at different times or maintain it while modifying the widget tree.

Flutter checks the previous state before re-rendering and if the previous widget is of the same type as the new one — it is going to maintain the old state.

We don’t want this if the data is changing as flutter will still reference the old data. Thus we need keys to uniquely identify the widget. This is because a new widget will have a different key from the previous one thus the old one is destroyed.

Types of Keys

  1. Valuekey
  2. Objectkey
  3. Uniquekey
  4. Globalkey

Valuekey

Commonly used in a list of children where the value of each child is unique and constant.

Objectkey

Same as the valuekey with the only difference being that it takes in a class object that holds data.

Uniquekey

In the situation where the children do not have unique values or don`t have a value at all, the Uniquekey is used to identify each child.

GlobalKey

This is the controversial one. The key with the potential to unlock all doors but may destroy the locks along.

The global key can be used to access a state of another widget from anywhere in the widget tree but it is expensive and there are better ways to do that such as Providers, Inherited Widgets, etc.

But it does have a few good and valid use cases such as Form validation. When assigned to a Form, one can access the FormStates public functions and variables and use them accordingly.

In order to use it, the widget is assigned the key must be stateful and its state public. ie no underscore, and you can only access the public variables only

That’s it for keys. Now get out there and keep unlocking your potential.

--

--

Dedan Ndungu
Dedan Ndungu

Written by Dedan Ndungu

Senior Mobile Engineer || Flutter Enthusiast || Technical Writer

Responses (1)

Write a response