嗨,我正在尝试创建一个有状态的小部件,它接受一些必需的参数和一些可选的参数。如果没有传递任何内容,可选的将有一个设置的默认值。我已经应用了与在一般类或函数中实现此目的相同的过程,但由于某种原因,在有状态小部件中使用它时它不喜欢它。这是为什么?有办法让它发挥作用吗?
当前从 VS code linting 获取此信息:
此类(或此类继承自的类)被标记为“@immutable”,但其一个或多个实例字段不是最终的:Example.inActivedartmust_be_immutable
这是我的代码:
class Example extends StatefulWidget {
Example({super.key, required this.name, required this.age, inActive = false});
final String name;
final int age;
bool? inActive;
@override
State<Example> createState() => _ExampleState();
}
class _ExampleState extends State<Example> {
@override
Widget build(BuildContext context) {
return Container();
}
}
感谢您花费时间和精力回答我的问题。
只需将 inActive 字段设置为 final。
class Example extends StatefulWidget {
Example({super.key, required this.name, required this.age, this.inActive = false});
final String name;
final int age;
final bool? inActive;
....