英文:
Initializing non-mutable fields in Stateful Widgets in Flutter
问题
在创建Flutter中的有状态(widget)小部件时,您可能希望小部件的某些字段不被改变。在这种情况下,我有困难确定是更好地始终从状态的widget
引用引用这些字段,还是更好地在状态中声明这些字段,并从小部件中获取任何初始值。例如:
class MyStatefulWidget extends StatefulWidget {
final bool? mutateMe; // 允许用户提供可变字段的初始值
final bool? doNotMutateMe; // 允许用户提供不打算更改的字段的值
MyStatefulWidget({ super.key, this.mutateMe, this.doNotMutuateMe });
@override State<MyStatefulWidget> createState() => MyStatefulWidgetState();
}
class MyStatefulWidgetState extends State<MyStatefulWidget> {
late bool mutateMe;
late bool doNotMutateMe; // <-- 这里:在状态中包括这个字段更好吗?
@override void initState() {
mutateMe = widget.mutateMe ?? true;
doNotMutateMe = widget.doNotMutateMe ?? false;
}
// ...
}
对于像doNotMutateMe
这样的字段,它不打算被修改,是否有意义在状态对象中重新创建该字段,或者始终只引用widget.doNotMutateMe
呢?
我已经了解到状态对象的寿命超过小部件,所以我很好奇这对此问题可能有什么影响。
英文:
When creating a stateful widget in flutter, you may want some fields of the widget to not be mutated. In that case, I'm having trouble trying to figure out if it is better to always reference those fields from the state's widget
reference, or if it's better to declare those fields in the state still, and get any initial values from the widget. For example:
class MyStatefulWidget extends StatefulWidget {
final bool? mutateMe; // allows the user to provide an initial value of a mutable field
final bool? doNotMutateMe; // allows the user to provide the value of a field that is not intended to be mutated
MyStatefulWidget({ super.key, this.mutateMe, this.doNotMutuateMe });
@override State<MyStatefulWidget> createState() => MyStatefulWidgetState();
}
class MyStatefulWidgetState extends State<MyStatefulWidget> {
late bool mutateMe;
late bool doNotMutateMe; // <-- HERE: is it better to include this field here?
@override void initState() {
mutateMe = widget.mutateMe ?? true;
doNotMutateMe = widget.doNotMutateMe ?? false;
}
// ...
}
For a field like doNotMutateMe
, that is not intended to be modified, does it make sense to re-create the field in the state object, or not, and always just refer to widget.doNotMutateMe
instead?
I've read that the state object outlives the widget, so I'm curious what implications that might have here?
答案1
得分: 1
我会更喜欢在状态类上使用widget.variableName
,如下所示:
class MyStatefulWidget extends StatefulWidget {
final bool? mutateMe;
final bool? doNotMutateMe;
const MyStatefulWidget({
super.key,
this.mutateMe = true,
this.doNotMutateMe = false,
});
@override
State<MyStatefulWidget> createState() => MyStatefulWidgetState();
}
英文:
As you've included , I will prefer using widget.variableName
on state class
class MyStatefulWidget extends StatefulWidget {
final bool? mutateMe;
final bool? doNotMutateMe;
const MyStatefulWidget({
super.key,
this.mutateMe = true,
this.doNotMutateMe = false,
});
@override
State<MyStatefulWidget> createState() => MyStatefulWidgetState();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论