Sobes.tech
Middle

What are GlobalKeys in Flutter and how are they used?

sobes.tech AI

Answer from AI

GlobalKey is a unique key that identifies a widget throughout the entire widget hierarchy.

Used for:

  1. Accessing the widget's State: Allows access to the StatefulWidget's State from anywhere in the widget tree.

    GlobalKey<_MyWidgetState> myWidgetKey = GlobalKey();
    
    // ...
    
    class MyWidget extends StatefulWidget {
      MyWidget({Key? key}) : super(key: key);
    
      @override
      _MyWidgetState createState() => _MyWidgetState();
    }
    
    class _MyWidgetState extends State<MyWidget> {
      String _text = "Initial";
    
      void updateText(String newText) {
        setState(() {
          _text = newText;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Text(_text);
      }
    }
    
    // ... somewhere else:
    myWidgetKey.currentState?.updateText("Updated");
    
  2. Preserving widget State when moving it in the tree: Useful when you need to move a widget to another part of the UI while keeping its state.

    GlobalKey keyForMovableWidget = GlobalKey();
    
    // ...
    
    Widget movableWidget = Container(
      key: keyForMovableWidget,
      color: Colors.blue,
      width: 100,
      height: 100,
    );
    
    // When moving movableWidget elsewhere in the tree,
    // its state will be preserved thanks to GlobalKey.
    
  3. Calling widget methods: Allows calling public methods of a widget from outside.

    GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
    
    // ...
    
    Scaffold(
      key: scaffoldKey,
      // ...
    );
    
    // ... somewhere else:
    scaffoldKey.currentState?.openDrawer();
    

It is important to remember that frequent use of GlobalKey can complicate the widget tree and hinder debugging. In most cases, it is preferable to use other state management mechanisms such as Provider, Riverpod, or Bloc. GlobalKey should only be used when other approaches are not applicable.

What are GlobalKeys in Flutter and how are they used… - sobes.tech