0

我有这样的流程。

  1. 当屏幕打开时,计时器启动(我将计时器功能放在 上initState)。
  2. 计时器结束后,我想再次重新倒计时。我尝试在中调用定时器功能,initStateonPressed定时器不再重新倒计时。

这是我的代码:

class _MyHomePageState extends State<MyHomePage> {
  Timer _timer;

  int _start = 10;

  void _startTimer() {
    const oneSec = Duration(seconds: 1);
    _timer = Timer.periodic(
      oneSec,
      (Timer timer) {
        if (_start == 0) {
          setState(() {
            timer.cancel();
          });
        } else {
          setState(() {
            _start--;
          });
        }
      },
    );
  }

  @override
  void initState() {
    super.initState();
    _startTimer();
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Timer:',
            ),
            Text(
              '$_start',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _startTimer,
        child: Icon(Icons.add),
      ),
    );
  }
}

我已经用关键字搜索,re-countdown timer in Flutter但没有找到解决方案。

4

2 回答 2

2

您需要进行这些更改。

  floatingActionButton: FloatingActionButton(
    onPressed: () {
      setState(() {
        _start = 10;
      });
      _startTimer();
    },
    child: Icon(Icons.add),
  )

  void _startTimer() {
    const oneSec = Duration(seconds: 1);
    _timer = Timer.periodic(
      oneSec,
      (_) {
        if (_start == 0) {
          setState(() {
            _timer.cancel();
          });
        } else {
          setState(() {
            _start--;
          });
        }
      },
    );
  }
于 2021-01-11T10:21:36.983 回答
0

那是因为您的 _start 变量为 0 您需要再次将其设置为 10 然后调用 startTimer

于 2021-01-11T10:19:30.623 回答