In Emily Fortuna's article (and video) she mentions:
GlobalKeys have two uses: they allow widgets to change parents anywhere in your app without losing state, or they can be used to access information about another widget in a completely different part of the widget tree. An example of the first scenario might if you wanted to show the same widget on two different screens, but holding all the same state, you’d want to use a GlobalKey.
Her article includes a gif demo of an app called "Using GlobalKey to ReuseWidget" but does not provide source code (probably because it's too trivial). You can also see a quick video demo here, starting at 8:30 mark: https://youtu.be/kn0EOS-ZiIc?t=510
How do I implement her demo? Where do I define the GlobalKey variable and how/where do I use it? Basically for example, I want to display a counter that counts up every second, and have it on many different screens. Is that something GlobalKey can help me with?
Global keys provide access to other objects that are associated with those elements, such as BuildContext. For StatefulWidgets, global keys also provide access to State. Widgets that have global keys reparent their subtrees when they are moved from one location in the tree to another location in the tree.
Calling a method of child widget from a parent widget is discouraged in Flutter. Instead, Flutter encourages you to pass down the state of a child as constructor parameters. Hence instead of calling a method of the child, you just call setState in the parent widget to update its children.
In flutter, the inherited widget is a base class that allows those classes to extend the information under the tree from it. Inherited widgets are also a kind of state management technique. It works by telling registered build references when a change occurs.
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<Example> { 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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With