问题描述
The instance member 'widget' can't be accessed in an initializer.
问题原因
"The instance member 'widget' can't be accessed in an initializer" 错误是因为在初始化器列表中(constructor initializer list)访问了 widget 成员。这是因为在构造函数的初始化器列表中,对象的属性(包括 widget)还没有被初始化,因此不能在这里访问它们。
有问题的源码
class CountdownTimer extends StatefulWidget {
final int duration;
final int numIterations;
final int breakTime;
const CountdownTimer({
Key? key,
required this.duration,
required this.numIterations,
required this.breakTime,
}) : super(key: key);
@override
State<CountdownTimer> createState() => _CountdownTimerState();
}
class _CountdownTimerState extends State<CountdownTimer> {
final String countDownMusic='assets/beat.mp3';
final String restMusic='assets/piano.mp3';
late Timer _timer;
double _timeProgress = 1.0;
double _numProgress = 1.0;
int rounds = widget.numIterations;
解决方法
int rounds = widget.numIterations;
这一句增加一个late修饰符
late int rounds = widget.numIterations;
标签:numIterations,widget,int,required,initializer,member,final
From: https://blog.51cto.com/u_15777557/8180893