简体   繁体   中英

Flutter: How to re-countdown timer

I have a flow like this.

  1. When the screen is open, the timer is started (I drop the timer function on initState ).
  2. After the timer is finished, I want to re-countdown the timer again. I try call the timer function on initState in the onPressed but the timer not re-countdown again.

This is my code:

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

I already googling with keyword re-countdown timer in Flutter but didn't find solution.

You need to make these changes.

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

and

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

that's because your _start variable is 0 you need to set it to 10 again then call startTimer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM