我有一个简单的代码段:
class CreateNewViewPage extends StatefulWidget {
final ComponentConfiguration currentComponentConfiguration = ComponentConfiguration(1, 1);
final Components components = Components(currentComponentConfiguration);
@override
State<StatefulWidget> createState() => _CreateNewViewPage();
}
不幸的是,当我想发送currentComponentConfiguration
到Components
类构造时,我得到以下信息:The instance member 'currentComponentConfiguration' can't be accessed in an initializer.
我该如何解决这个问题?
您不能使用非静态变量来初始化另一个非静态变量。要么使currentComponentConfiguration
静态成员或做components
在创建对象State
类(_CreateNewViewPageState
)。
使用静态
class CreateNewViewPage extends StatefulWidget {
static final ComponentConfiguration currentComponentConfiguration = ComponentConfiguration(1, 1);
final Components components = Components(currentComponentConfiguration);
@override
_CreateNewViewPageState createState() => _CreateNewViewPageState();
}
使用状态类
class CreateNewViewPage extends StatefulWidget {
final ComponentConfiguration currentComponentConfiguration = ComponentConfiguration(1, 1);
@override
_CreateNewViewPageState createState() => _CreateNewViewPageState();
}
class _CreateNewViewPageState extends State<CreateNewViewPage> {
Components components;
@override
void initState() {
super.initState();
components = Components(widget.currentComponentConfiguration);
}
@override
Widget build(BuildContext context) {
return Text('Hello, World!', style: Theme.of(context).textTheme.headline4);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句