D
Flutter CoreEasy20 XP3 min read

What is the difference between LocalKey and GlobalKey?

TL;DR: LocalKey (ValueKey, ObjectKey, UniqueKey) identifies a widget within its parent's children list; GlobalKey uniquely identifies a widget across the entire app tree and provides access to its State and RenderObject.

Full Answer

LocalKeys are scoped to the parent's children. They're used in lists and animated lists to preserve state during reorders. GlobalKeys provide a unique reference that works across the entire widget tree — useful for accessing FormState, ScaffoldState, or moving widgets between different parent trees.

⚠️

GlobalKey is expensive. Each GlobalKey maintains a map entry in the global registry. Avoid creating them in build() — create them in initState() or as class fields. Never use GlobalKey when a LocalKey or state management solution will do.

Interview Tip

💡

Common use cases for GlobalKey: accessing FormState.validate(), opening a Scaffold's drawer from outside the Scaffold, or building an app tour that needs to access multiple arbitrary widgets.

#keys#globalkey#localkey#reconciliation