Flutter:如何重新倒数计时器

Flutter: How to re-countdown timer

我有这样的流程。

  1. 当屏幕打开时,开始计时(我把计时功能放在initState上)。
  2. 计时器结束后,我想重新倒计时一次。我尝试在 onPressed 中调用 initState 上的计时器功能,但计时器不会再次重新倒计时。

这是我的代码:

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 进行了谷歌搜索,但没有找到解决方案。

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

您需要进行这些更改。

  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--;
          });
        }
      },
    );
  }