gpt4 book ai didi

flutter - 如何在改变 parent 时使用 `GlobalKey` 来维护小部件的状态?

转载 作者:IT王子 更新时间:2023-10-29 06:36:19 26 4
gpt4 key购买 nike

在 Emily Fortuna 的文章(和视频)中,她提到:

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.

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

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

最佳答案

使用 GlobalKey 的最常见用例在树周围移动小部件是有条件地将“子”包装到另一个小部件中,如下所示:

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

使用这样的代码,您很快就会注意到,如果 child 是有状态的,切换 foo 将使 child 失去其状态,即通常出乎意料。

为了解决这个问题,我们会让我们的小部件有状态,创建一个 GlobalKey , 并将 child 包装成 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;
}
}

关于flutter - 如何在改变 parent 时使用 `GlobalKey` 来维护小部件的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56895273/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com