You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter定时器无法在进度达1时停止问题排查求助

问题原因与解决方案

你遇到的问题是浮点数精度误差导致的。因为0.1是二进制无法精确表示的小数,累加10次后,progress的实际值并不会刚好等于1,而是类似0.9999999999999999或者1.0000000000000002,所以progress == 1的判断永远不会成立,定时器也就无法停止。

解决方案一:修改判断条件

将判断逻辑改为progress >= 1,同时在触发停止时把进度修正为精确的1,避免数值溢出:

void startTimer() {
  Timer.periodic(const Duration(seconds: 1), (timer) {
    setState(() {
      if (progress >= 1) {
        progress = 1; // 修正为精确值
        timer.cancel();
      } else {
        progress += 0.1;
      }
    });
  });
}

解决方案二:用整数计数避免浮点数误差(更可靠)

改用整数计数,再通过计算转换为进度值,彻底规避浮点数精度问题:

class _MyHomeState extends State<MyHome> {
  int count = 0; // 整数计数,从0到10对应进度0到1
  double get progress => count / 10; // 转换为进度值

  void startTimer() {
    Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (count == 10) {
          timer.cancel();
        } else {
          count += 1;
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Stack(
            alignment: Alignment.center,
            children: [
              Text(progress.toStringAsFixed(1)),
              SizedBox(
                height: 300,
                width: 300,
                child: CircularProgressIndicator(
                  value: progress,
                  color: Colors.deepOrange,
                ),
              )
            ],
          ),
          const SizedBox(
            height: 50,
          ),
          ElevatedButton(
              onPressed: () {
                setState(() {
                  count = 0; // 重置计数
                  startTimer();
                });
              },
              child: const Text('Start'))
        ],
      ),
    );
  }
}

这种方式逻辑更清晰,完全不会出现判断失效的情况,是处理这类进度问题的更优方案。

内容的提问来源于stack exchange,提问作者Hana.HD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 02:09:58