Flutter使用CountDownTimer时onComplete参数类型错误怎么解决
问题原因
- 你自定义的
CountDownTimer类中onComplete的函数类型,和CircularCountDownTimer组件要求的onComplete参数类型不匹配,直接传递函数引用时触发了类型校验报错。 - 额外的语法错误:
setState的回调函数要求是同步的VoidCallback类型,你在回调里加了async修饰,本身也会引发类型不兼容问题。
修复方案
- 先修正
setState的异步写法,把异步弹窗逻辑移到setState外部执行:
CountDownTimer _countDownTimer = CountDownTimer( duration: kWorkDuration, fillColor: Colors.pink, onComplete: () { // setState回调仅处理同步状态更新 setState(() { widget.timesCompleted[indexTimesCompleted] = Icon( Icons.brightness_1_rounded, color: Colors.pink, size: 5.0, ); indexTimesCompleted++; }); // 异步逻辑放到setState外部执行 NDialog( dialogStyle: DialogStyle(titleDivider: true), title: Text("Timer Completed"), content: Text("Time to break."), actions: <Widget>[ ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateColor.resolveWith( (states) => Colors.green), ), child: Text("Start a short break"), onPressed: () {}), ], ).show(context); }, );
- 给
CircularCountDownTimer的onComplete赋值时,手动包裹一层匿名函数适配类型,避免直接传引用的类型推断异常,如果你的onComplete是可空类型,同时加上空安全校验:
CircularCountDownTimer clock = CircularCountDownTimer( controller: _clockController, isReverseAnimation: true, ringColor: Color(0xff0B0C19), height: height, width: width, autoStart: false, duration: _countDownTimer.duration * 60, isReverse: true, textStyle: TextStyle(color: Colors.white), fillColor: _countDownTimer.fillColor, backgroundColor: Color(0xFF2A2B4D), strokeCap: StrokeCap.round, // 替换原来的直接传值,手动适配类型 onComplete: () { _countDownTimer.onComplete?.call(); }, );
内容的提问来源于stack exchange,提问作者RoRo Studio
相关产品推荐
相关产品推荐

