flutter开发报错The instance member ‘widget‘ can‘t be accessed in an initializer

请添加图片描述

问题描述

The instance member ‘widget’ can’t be accessed in an initializer.

image.png

问题原因

“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;

结束语
Flutter是一个由Google开发的开源UI工具包,它可以让您在不同平台上创建高质量、美观的应用程序,而无需编写大量平台特定的代码。我将学习和深入研究Flutter的方方面面。从基础知识到高级技巧,从UI设计到性能优化,欢饮关注一起讨论学习,共同进入Flutter的精彩世界!

猜你喜欢

转载自blog.csdn.net/yikezhuixun/article/details/134238802