What are Keys in the Stateless widgets class?

TLDR: All widgets should have a Key key as optional parameter or their constructor.
Key is something used by flutter engine at the step of recognizing which widget in a list as changed.


It is useful when you have a list (Column, Row, whatever) of widgets of the same type that can potentially get removed/inserted.

Let’s say you have this (code not working, but you get the idea) :

AnimatedList(
  children: [
    Card(child: Text("foo")),
    Card(child: Text("bar")),
    Card(child: Text("42")),
  ]
)

Potentially, you can remove any of these widgets individually with a swipe.

The thing is, our list has an animation when a child is removed. So let’s remove “bar”.

AnimatedList(
  children: [
    Card(child: Text("foo")),
    Card(child: Text("42")),
  ]
)

The problem: Without Key, flutter won’t be able to know if the second element of your Row disappeared. Or if it’s the last one that disappeared and the second has its child change.

So without Key, you could potentially have a bug where your leave animation will be played on the last element instead!


This is where Key takes place.

If we start our example again, using key we’d have this :

AnimatedList(
  children: [
    Card(key: ObjectKey("foo"), child: Text("foo")),
    Card(key: ObjectKey("bar"), child: Text("bar")),
    Card(key: ObjectKey("42"), child: Text("42")),
  ]
)

notice how the key is not the child index but something unique to the element.

From this point, if we remove “bar” again, we’ll have

AnimatedList(
  children: [
    Card(key: ObjectKey("foo"), child: Text("foo")),
    Card(key: ObjectKey("42"), child: Text("42")),
  ]
)

Thanks to key being present, flutter engine now knows for sure which widget got removed. And now our leave animation will correctly play on “bar” instead of “42”.

Leave a Comment