When to Use Keys - Flutter Widgets 101 Ep. 4

[MUSIC PLAYING]
EMILY: Hey, I'm Emily from the Flutter team.
In this video, we're going to talk about using
the key parameter on widgets.
If you're wondering what the heck a widget is,
I recommend going back to the first video
in the series, where we introduced the building
blocks of Flutter.
Keys preserve state when widgets move around
in your widget tree.
They can be used to preserve the user's scroll location,
or keeping state when modifying a collection.
In this video, we'll cover three things--
when you need keys, where to put them in your widget tree,
and which key is right for you.
[BELL DINGING]
So when do you need to use keys?
Most of the time, you don't.
But if you find yourself adding, removing, or reordering
collection of widgets of the same type that hold some state,
it's key time.
No, key time.
An example of this is a to-do list app.
When using the app, you want to reorder the items based
on your to-do list based on priority,
and then remove them when you're done.
Another example is the Hacker News app in the Flutter Boring
Show.
Adding keys prevented the story widgets
from incorrectly picking up old state when
the list view was rebuilt.
To illustrate why you need keys in this situation,
I wrote an extremely simple app with two randomly colored
widgets that swap places when you tap a button.
Here's the code for the app.
It consists of a stateful widget,
called PositionedTiles, that constructs two stateless tiles,
and places them in a row.
When I tap the Floating Action button down at the bottom,
it swaps their position in the list, as expected.