问题描述
应该在哪里保留最终值?
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.
这篇关于是否将最终字段保留在小部件或州?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!