D
Widget TreeIntermediate30 XP3 min read

What is the difference between GlobalKey and LocalKey?

TL;DR: LocalKey (ValueKey, ObjectKey, UniqueKey) identifies a widget among its siblings. GlobalKey uniquely identifies a widget across the entire app, allowing access to its State and RenderObject from anywhere.

Full Answer

Keys serve two purposes: helping reconciliation and providing programmatic access. The scope distinguishes GlobalKey from LocalKey.

AspectLocalKeyGlobalKey
ScopeAmong siblings onlyEntire app
TypesValueKey, ObjectKey, UniqueKeyGlobalKey<T extends State>
Access StateNoYes via key.currentState
Access RenderObjectNoYes via key.currentContext!.findRenderObject()
PerformanceCheapRegistered in a global map โ€” use sparingly
๐ŸŽฏ

Avoid GlobalKey as a dependency injection mechanism. Use it only for: Form validation (FormState), imperative navigation, or getting RenderBox for screenshots/overlays.

Code Examples

dartGlobalKey for Form validation
Output
Tapping Submit triggers validation; shows error text if field is empty, proceeds if valid

Common Mistakes

  • โœ—Creating a GlobalKey inside build() โ€” recreates the key on every rebuild, breaking its purpose
  • โœ—Using GlobalKey to share data between widgets โ€” use state management instead

Interview Tip

๐Ÿ’ก

The Form/GlobalKey pattern is the canonical use case every interviewer knows. Mention it first, then note the caveats about performance.

#GlobalKey#LocalKey#ValueKey#UniqueKey#keys