我的计时器快疯了,它减少了 2、3 秒,而它应该只有 1 秒(每秒调用一次计时器)

My Timer is going crazy , It decrements 2 , 3 seconds when it should only 1 (Timer is being called every second)

一个用Flutter写的非常简单的定时器。但是计时器的 time 从 1 跳到 3 ,从 3 跳到 6 (疯狂)并且它在应该停止时转到 -(负)值。使用 setState 来更新时间。 这是代码

import 'package:flutter/material.dart';
import 'dart:async';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Timer Demo',
      home: MyHomePage(title: 'My Timer'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  void updateUI()=>setState((){});
  var timer=MyTimer();
  
  @override
  Widget build(BuildContext context) {
    timer.start(updateUI);
    return Scaffold(
      appBar: AppBar(
        title: Text('Timer'),
      ),
      body: Center(
        child: Text(timer.time.toString()),
      ),
    );
  }
}

class MyTimer{
  int time=10;
  
  start(Function callback){
    Timer.periodic((Duration (seconds:1)),(timer){
      time--;
      callback();
      if(time<1) timer.cancel();
    });
  }
}

我正在为 windows 桌面版构建应用程序

您在 build() 方法中启动计时器,这意味着每次 UI 重新呈现时,都会在 MyTimer class 中调用 start() 函数.

你可以尝试在initState方法中调用timer.start(updateUI)(添加到_MyHomePageState),例如:

@override
void initState() {
  super.initState();
  timer.start(updateUI);
}