Flutter Keys: Easy Guide to Widget Control and State

Syed Abdul Basit
3 min readFeb 22, 2024

--

Understanding Flutter Keys: A Simple Guide for Everyone

Every Widget has a key. Keys is an object that is used to identify a widget uniquely in a widget tree and also needs to store a widget state having the same type of data.

In the magical realm of Flutter, every widget is like a unique puzzle piece, and keys are the secret spells that help these pieces find their place in the grand puzzle of your app.
But when you start juggling a bunch of widgets that are twinsies in type and have their own little secrets (aka states), that’s when keys become your best friends.

Good News: 🎉 Remember, in the land of Stateless Widgets, keys are like unicorns 🦄 — rare and often unnecessary.

🔑 Knowing When to Use Keys
Most of the time we don’t na, but if you find yourself adding, removing and reordering a collection of widget of the same type that holds some state.

🔄 Swapping Tiles: A Colorful Puzzle
Here’s where things get interesting. When you swap stateless tiles, Flutter just checks the type. But with stateful tiles, it’s a different ball game. You need to give them keys, like little ID badges, so Flutter knows who’s who when they switch places.

🖼️ Flutter’s Display Decisions
Flutter uses the element tree and the state info to decide what to show on your screen. Without keys, stateful widgets get all confused during a swap — like sending two kids to camp and getting them back with swapped backpacks.

🌳 Element Tree: The Backbone of Your App
The element tree is extremely simple, only holding information about the type of each widget and a reference to the children element. You can think the element tree is like a skeleton of your app.

🔑 Key to Success: Where to Place Them?
Keys are like the secret sauce in your widget recipe. You sprinkle them at the top of your widget subtree that you want to keep track of. But remember, it’s not always the first stateful widget that gets the key!

TYPES OF KEYS

🔍 OBJECT KEY: When your widget holds a mix of complex data, like in an address book app where each user’s info is a unique combo of name, birthday, etc., an Object Key is the way to go. It’s perfect for situations where each piece might not be unique alone, but together, they’re one of a kind.

🌟 UNIQUE KEY: Got a bunch of widgets with the same look or value? Want to make sure each one stands out as its own star? That’s where the Unique Key shines. It ensures every widget is recognized as an individual, even in a crowd.

📜 PAGE STORAGE KEY: Ever want to keep track of where you scrolled to in an app? Page Storage Key is like a bookmark for your app’s scroll position, saving it for next time.

🌐 GLOBAL KEY: This key is a multitasker. It lets widgets switch parents in your app without losing their identity or lets you peek into a widget’s world, even if it’s in a totally different part of your app. Think of it like having a VIP pass to move freely and keep everything you need.

import 'package:flutter/material.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Draggable List Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: DraggableListPage(),
);
}
}

class DraggableListPage extends StatefulWidget {
@override
_DraggableListPageState createState() => _DraggableListPageState();
}

class _DraggableListPageState extends State<DraggableListPage> {
List<String> items = List.generate(10, (index) => 'Item ${index + 1}');

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Draggable List Example'),
),
body: ReorderableListView(
padding: EdgeInsets.symmetric(vertical: 8.0),
children: items
.map((item) => ListTile(
key: Key(item),
title: Text(item),
leading: Icon(Icons.drag_handle),
))
.toList(),
onReorder: (oldIndex, newIndex) {
setState(() {
if (oldIndex < newIndex) {
newIndex -= 1;
}
final String item = items.removeAt(oldIndex);
items.insert(newIndex, item);
});
},
),
);
}
}

Reference:
https://medium.com/flutter/keys-what-are-they-good-for-13cb51742e7d
https://api.flutter.dev/flutter/foundation/Key-class.html

--

--