Flutter - Create a countdown widget

Viewed 20547

I am trying to build a countdown widget. Currently, I got the structure to work. I only struggle with the countdown itself. I tried this approach using the countdown plugin:

class _Countdown extends State<Countdown> {

  int val = 3;

  void countdown(){
    CountDown cd = new CountDown(new Duration(seconds: 4));

    cd.stream.listen((Duration d) {
      setState((){
        val = d.inSeconds;
      });
    });

  }

  @override
  build(BuildContext context){
    countdown();
    return new Scaffold(
      body: new Container(
        child: new Center(
          child: new Text(val.toString(), style: new TextStyle(fontSize: 150.0)),
        ),
      ),
    );
  }
}

However, the value changes very weirdly and not smooth at all. It start twitching. Any other approach or fixes?

5 Answers

Why not use a simple TweenAnimationBuilder its easy to use and you don't need to manage any stream controllers or worry about using streams and disposing them off etc;

TweenAnimationBuilder<double>(
                duration: Duration(seconds: 10),
                tween: Tween(begin: 100.0, end: 0.0),
                onEnd: () {
                  print('Countdown ended');
                },
                builder: (BuildContext context, double value, Widget child) {
                  return Padding(
                      padding: const EdgeInsets.symmetric(vertical: 5),
                      child: Text('${value.toInt()}',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              color: Colors.black,
                              fontWeight: FontWeight.bold,
                              fontSize: 40)));
                }),

here's the dartpad example to playaround output:

enter image description here

originally answered here

Related