How to use `GlobalKey` to maintain widgets' states when changing parents?

前端 未结 3 551
独厮守ぢ
独厮守ぢ 2020-12-25 15:18

In Emily Fortuna\'s article (and video) she mentions:

GlobalKeys have two uses: they allow widgets to change parents anywhere in your app without lo

3条回答
  •  自闭症患者
    2020-12-25 16:18

    The most common use-case of using GlobalKey to move a widget around the tree is when conditionally wrapping a "child" into another widget like so:

    Widget build(context) {
      if (foo) {
        return Foo(child: child);
      }
      return child;
    }
    

    With such code, you'll quickly notice that if child is stateful, toggling foo will make child lose its state, which is usually unexpected.

    To solve this, we'd make our widget stateful, create a GlobalKey, and wrap child into a KeyedSubtree

    Here's an example:

    class Example extends StatefulWidget {
      const Example({Key key, this.foo, this.child}) : super(key: key);
    
      final Widget child;
      final bool foo;
    
      @override
      _ExampleState createState() => _ExampleState();
    }
    
    class _ExampleState extends State {
      final key = GlobalKey();
    
      @override
      Widget build(BuildContext context) {
        final child = KeyedSubtree(key: key, child: widget.child);
    
        if (widget.foo) {
          return Foo(child: child);
        }
        return child;
      }
    }
    

提交回复
热议问题