Flutter API文档 - GlobalKey

GlobalKey<T extends State> class

A key that is unique across the entire app.
在整个app中唯一的key。

Global keys uniquely identify elements. 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.
作为全局键唯一标识元素, Global key提供对其他对象的访问,这些对象是与element关联的,例如 BuildContext。 对于 StatefulWidgets,Global key也提供对 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. In order to reparent its subtree, a widget must arrive at its new location in the tree in the same animation frame in which it was removed from its old location in the tree.
当Widget从树中的一个位置移动到树中的另一个位置时,具有global key的Widget将重新设置其子树。 为了重新设置它的子树,在同一动画帧时间里,一个Widget必须到达它在树中的新位置,同时从树中的旧位置移除。

Reparenting an Element using a global key is relatively expensive, as this operation will trigger a call to State.deactivate on the associated State and all of its descendants; then force all widgets that depends on an InheritedWidget to rebuild.
使用global key重新设置Element的成本相对较高,因为此操作将触发对关联State及其所有后代的 State.deactivate 的调用; 然后强制所有依赖于 InheritedWidget 的widget进行rebuild。

If you don’t need any of the features listed above, consider using a Key, ValueKey, ObjectKey, or UniqueKey instead.
如果你不需要上面列出的任何功能,请考虑改用 Key、ValueKey、ObjectKey 或 UniqueKey。

You cannot simultaneously include two widgets in the tree with the same global key. Attempting to do so will assert at runtime.
你不能同时在树中包含具有相同global key的两个widget。 尝试这样做将在运行时assert。

Pitfalls - 陷阱

GlobalKeys should not be re-created on every build. They should usually be long-lived objects owned by a State object, for example.
不应在每次构建时重新创建 GlobalKeys。 例如,它们通常应该是由 State 对象拥有的长期对象。

Creating a new GlobalKey on every build will throw away the state of the subtree associated with the old key and create a new fresh subtree for the new key. Besides harming performance, this can also cause unexpected behavior in widgets in the subtree. For example, a GestureDetector in the subtree will be unable to track ongoing gestures since it will be recreated on each build.
在每个build上创建一个新的 GlobalKey 将丢弃与旧key关联的子树的状态,并为新key创建一个新的新子树。 除了损害性能之外,这还可能导致子树中的widget出现异常行为。 例如,子树中的 GestureDetector 将无法跟踪正在进行的手势,因为它将在每次build时重新创建。

Instead, a good practice is to let a State object own the GlobalKey, and instantiate it outside the build method, such as in State.initState.
相反,一个好的做法是让 State 对象拥有 GlobalKey,并在 build 方法之外实例化它,例如在 State.initState 中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值