Sam Cromer
Sam Cromer

Reputation: 2213

Countdown in text flutter

We need to create a 5 minute countdown text object in Flutter, once the countdown reaches zero then we need to launch a new screen. here is the current code:

 Container(
                                    margin: EdgeInsets.only(left: 0.0,top: 60.0, bottom: 50.0, right:0.0),    
                                    child: Text(

                '5:00', style: new TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 100.0 ))
              ,

                                     ), 

Upvotes: 0

Views: 349

Answers (1)

danypata
danypata

Reputation: 10175

I usually don't post just sample code, but I was in the mood of coding a bit in flutter. So here's my quick suggestion on how you can implement this:

class _MyHomePageState extends State<MyHomePage> {
  TickViewModel _viewModel; 
  int _seconds;
  StreamSubscription<int> _tickSubscription;

  @override
  void initState() {
    super.initState();
    _viewModel = TickViewModel();
    _tickSubscription = _viewModel._tickStream.listen((newTime) {
      if (newTime == 0) {
        //TODO: DO THE SCREEN CHANGE HERE;
      }
      setState(() {
        _seconds = newTime;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text("My Flutter App"),
          backgroundColor: Colors.red,
        ),
        body: Text(_computeTime()));
  }

  String _computeTime() {
    if (_seconds == null) {
      return "-";
    }
    String minutes = "${_seconds ~/ 60}".padLeft(2, "0");
    String seconds = "${_seconds % 60}".padLeft(2, "0");
    return "$minutes:$seconds";
  }

  @override
  void dispose() {

    //We cleanup the stuffs here
    _tickSubscription.cancel();
    _viewModel.destroy();
    super.dispose();
  }
}

class TickViewModel {
  static const int _fiveMinutes = 5 * 60;
  StreamController<int> _ticker;

  Stream<int> get _tickStream => _ticker.stream;

  Timer _timer;
  final int seconds;
  int _internalSeconds;

  TickViewModel({this.seconds = _fiveMinutes}) : _internalSeconds = seconds {
    _ticker = StreamController(onListen: () {
      //start timer only when we have a subscriber
      _startTimer();
    }, onCancel: () {
      _timer.cancel();
    });
  }

  void _startTimer() {
    //start timer to tick every 1 second
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      _internalSeconds -= 1;
      if (_internalSeconds < 0) {
        _timer.cancel();
      } else {
        _ticker.add(_internalSeconds);
      }
    });
  }

  void destroy() {
    _ticker.close();
    _timer.cancel();
  }
}

Upvotes: 1

Related Questions