是否将最终字段保留在小部件或州?

编程入门 行业动态 更新时间:2024-10-27 15:18:37
本文介绍了是否将最终字段保留在小部件或州?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

应该在哪里保留最终值?

Where should one keep final values?

在 StatefulWidget (当然是我的子类)实例和访问中从 State (子类)通过 widget.thatFinalField 或

In the StatefulWidget (my subclass of course) instance and access it from the State (subclass) via widget.thatFinalField, or

位于州本身。我已经看过这两种方法。每种方法都有利弊吗?

In the State itself. I've seen both approaches already.. Any pros and cons for each of them?

推荐答案

您应该存储<$ c $在 StatefulWidget 上的c> final 成员字段(通过构造函数参数传递),并将其公开。

You should store final member fields (which are passed via constructor arguments) on the StatefulWidget and make them public.

与 StatefulWidget 关联的 State 应该仅使用默认构造函数(无参数),并且其成员字段应该是私有的(以 _ 开头)并且是可变的。内联或在需要昂贵或异步工作的 initState 中初始化它们。

The StatefulWidget's associated State should use only the default constructor (no arguments), and its member fields should be private (starting with a _) and mutable. Initialize them inline or in initState if expensive or async work is necessary.

此模式允许 StatefulWidget 将在其父级调用 setState 时使用新的构造函数参数重新创建/重建,同时重新使用以前的状态,并使其值存储在其可变成员字段中。

This pattern allows the StatefulWidget to be recreated/rebuilt with new constructor arguments when its parents call setState, while re-using the previous State and letting it keep the values stored in its mutable member fields.

更多推荐

是否将最终字段保留在小部件或州?

本文发布于:2023-11-13 14:09:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584525.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   部件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!