cft

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

Get to Know the types of keys in the Flutter framework and how to use them


user

Dedan Ndungu

2 years ago | 2 min read

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.

Uploaded by Filip on Unsplash

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.

Upvote


user
Created by

Dedan Ndungu

Living on the Edge


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles