Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...