本文介绍了更改父母时如何使用"GlobalKey"维护小部件的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在艾米丽·福图纳(Emily Fortuna)的文章(和视频)中,她提到:

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

她的文章包括一个名为使用GlobalKey到ReuseWidget"的应用程序的gif演示,但没有提供源代码(可能是因为它太琐碎了).您还可以在此处从8:30标记开始观看快速视频演示: https://youtu. be/kn0EOS-ZiIc?t = 510

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

如何实施她的演示?我在哪里定义GlobalKey变量以及如何/在哪里使用它?例如,基本上,我想显示一个每秒计数的计数器,并在许多不同的屏幕上显示该计数器.这是GlobalKey可以帮助我的吗?

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?

推荐答案

使用GlobalKey在树上移动小部件的最常见用例是有条件地将孩子"包装到另一个小部件中,例如: /p>

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;
}

使用这样的代码,您会很快注意到,如果child是有状态的,则切换foo会使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.

为解决此问题,我们将使小部件成为有状态的,创建一个GlobalKey,然后将child包装到KeyedSubtree

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

这是一个例子:

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;
  }
}

这篇关于更改父母时如何使用"GlobalKey"维护小部件的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 20:55