no_logic_in_create_state
不要在 createState 中放置任何逻辑。
详情
#不要在 createState()
中放置任何逻辑。
createState()
的实现应该返回 State 对象的新实例,并且不应执行其他任何操作。由于状态访问首选通过 widget
字段,因此也应避免使用自定义构造函数参数将数据传递给 State
对象,因此,State 构造函数必须不传递任何参数。
错误示例
dart
MyState global;
class MyStateful extends StatefulWidget {
@override
MyState createState() {
global = MyState();
return global;
}
}
dart
class MyStateful extends StatefulWidget {
@override
MyState createState() => MyState()..field = 42;
}
dart
class MyStateful extends StatefulWidget {
@override
MyState createState() => MyState(42);
}
正确示例
dart
class MyStateful extends StatefulWidget {
@override
MyState createState() {
return MyState();
}
}
启用
#要启用 no_logic_in_create_state
规则,请在你的 analysis_options.yaml
文件中的 linter > rules 下添加 no_logic_in_create_state
analysis_options.yaml
yaml
linter:
rules:
- no_logic_in_create_state
如果你改为使用 YAML 映射语法来配置 linter 规则,请在 linter > rules 下添加 no_logic_in_create_state: true
analysis_options.yaml
yaml
linter:
rules:
no_logic_in_create_state: true
除非另有说明,否则本网站上的文档反映了 Dart 3.7.1 版本。页面上次更新于 2025-03-07。 查看源代码 或 报告问题。