class RoutePage extends StatefulWidget {
final LatLng? pickUp;
final LatLng? dropOff;
RoutePage({required this.pickUp, required this.dropOff});
@override
_RoutePage createState() => _RoutePage();
}
class _RoutePage extends State<RoutePage> {
Set<Marker> _markers = {};
LatLng _origin;
LatLng _destination;
void initState() {
super.initState();
final _origin = widget.pickUp;
final _destination = widget.dropOff;
}
@override
Widget build(BuildContext context) {
...
}
在我的代码中,尽管我已在 initState() 中初始化了 _origin 和 _destination,但我仍然收到错误消息“必须初始化不可为 null 的实例字段 '_origin'”。添加late也不起作用...我也尝试添加setState,但它也不起作用。
最佳答案
这些变量未初始化,因为您正在 initState()
函数内重新创建它们:
void initState() {
super.initState();
final _origin = widget.pickUp; // <-- Recreating _origin here
final _destination = widget.dropOff; // <-- Recreating _destination here
}
在 Dart 中允许有同名的变量,因为在函数内部有不同的作用域。因此,这里不会出现错误,但由于您使用的是 final
关键字,因此您正在重新创建这些变量。要解决此问题,请不要在 initState()
函数中使用 Final:
void initState() {
super.initState();
_origin = widget.pickUp; // <-- Assigning a value to _origin here
_destination = widget.dropOff; // <-- Assigning a value to _destination here
}
关于flutter - initState() 中的变量未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71311397/