gpt4 book ai didi

flutter - 我们何时应该在Flutter小部件构造函数中指定Key参数?

转载 作者:行者123 更新时间:2023-12-03 04:34:38 26 4
gpt4 key购买 nike

我对Flutter&Dart非常陌生。从多个来源阅读了一些代码之后,我想知道在实现Flutter小部件构造函数时是否应该指定Key key参数。我发现一些代码不使用Key key参数,而其他代码则广泛使用它。
以下代码段是从StatelessWidget class部分复制而来的。它使用Key key参数。

class Frog extends StatelessWidget {
const Frog({
Key key,
this.color = const Color(0xFF2DBD3A),
this.child,
}) : super(key: key);

final Color color;
final Widget child;

@override
Widget build(BuildContext context) {
return Container(color: color, child: child);
}
}

我们何时应该在Flutter小部件构造函数中指定 Key参数?

最佳答案

默认情况下,框架根据它们的runtimeType和它们显示的顺序来匹配当前和先前版本中的窗口小部件。使用键时,框架要求两个小部件具有相同的键以及相同的runtimeType。
键在构建许多相同类型的窗口小部件实例的窗口小部件中最有用。例如,ShoppingList小部件,它仅构建足够的ShoppingListItem实例以填充其可见区域:

Without keys, the first entry in the current build would always sync with the first entry in the previous build, even if, semantically, the first entry in the list just scrolled off screen and is no longer visible in the viewport.


By assigning each entry in the list a “semantic” key, the infinite list can be more efficient because the framework syncs entries with matching semantic keys and therefore similar (or identical) visual appearances. Moreover, syncing the entries semantically means that state retained in stateful child widgets remains attached to the same semantic entry rather than the entry in the same numerical position in the viewport.


看一下这个视频,来自flutter团队: https://www.youtube.com/watch?v=kn0EOS-ZiIc&ab_channel=GoogleDevelopers

关于flutter - 我们何时应该在Flutter小部件构造函数中指定Key参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64326986/

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