Problem Statement
What is GlobalKey and when should you use it? What are its performance implications?
Explanation
GlobalKey uniquely identifies a widget across the entire app and provides access to the widget's State, Element, or RenderObject from anywhere in the code. Unlike local Keys which only identify widgets within their parent, GlobalKey allows you to access widget state or call methods on a widget's State object from outside the widget tree, making it powerful but expensive.
Use GlobalKey when you need to access widget state from outside, like accessing a Form widget's state to validate with formKey.currentState.validate(), or accessing a Scaffold to show SnackBars with scaffoldKey.currentState.showSnackBar(). GlobalKey is also necessary when you need to preserve state while moving a widget to a completely different location in the tree, as it maintains state even during major restructuring.
GlobalKey has performance costs because Flutter must maintain a global registry of all GlobalKeys and their associated widgets, and looking up GlobalKeys requires searching this registry. Creating too many GlobalKeys can impact performance. The key also prevents widget reuse and optimization because Flutter must ensure the globally-keyed widget maintains its identity and state.
Best practices: Use GlobalKey sparingly, only when absolutely necessary. For form validation, use Form with GlobalKey<FormState>. For scaffold operations, use ScaffoldMessenger.of(context) instead of GlobalKey<ScaffoldState> when possible (newer approach). For most state access needs, consider state management solutions like Provider, Bloc, or callbacks instead of GlobalKey. Avoid using GlobalKey just for convenience - only use it when you genuinely need global state access or state preservation across major tree changes.

