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.
| Aspect | LocalKey | GlobalKey |
|---|---|---|
| Scope | Among siblings only | Entire app |
| Types | ValueKey, ObjectKey, UniqueKey | GlobalKey<T extends State> |
| Access State | No | Yes via key.currentState |
| Access RenderObject | No | Yes via key.currentContext!.findRenderObject() |
| Performance | Cheap | Registered 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