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的精彩世界!
  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值