defemz
defemz

Reputation: 581

How do i pause and resume quiver.async CountdownTimer in flutter

i am trying to implement Countdown Timer in flutter. I got it working but cannot implement Pause and Resume feature of the class. Below is what i have tried:

import 'package:flutter/material.dart';   
import 'package:quiver/async.dart';

     void startTimer() {
        CountdownTimer countDownTimer = new CountdownTimer(
          new Duration(seconds: _start),
          new Duration(seconds: 2),
        );

        var sub = countDownTimer.listen(null);
        sub.onData((duration) {
         // Here i tried try to check a bool variable and pause the timer


    if(pauseTimer == true){
        sub.pause();
      }

     // Here i tried try to check a bool variable and resume the timer

    else if(pauseTimer == false){
            sub.resume();
          }
          setState(() {
            _current = _start - duration.elapsed.inSeconds;

          });

            if(_current == 0){
              //Do something here..
              }
        });




        sub.onDone(() {
          print("Done");
          sub.cancel();
        });

      }

The problem however is that only Pause is working, while the Resume is not working. Please any idea how to get both Pause and Resume working from button click. Thanks

Upvotes: 0

Views: 1320

Answers (1)

Jagraj Singh
Jagraj Singh

Reputation: 4391

sub.resume() is not working because after pausing the timer onData does not trigger. You can simply make a single FlatButton and implement onTap just like this.

StreamSubscription sub; // declare it as a class variable and then assign it in function

bool isPaused =false; /// your state class variable
onTap :(){
    if(isPaused)
        sub?.resume(); // performing a null check operation here...
    else
        sub?.pause(); // ...if sub is null then it won't call any functions
}

//// Note:- make sure to cancel sub like 
 sub?.cancel();

Upvotes: 2

Related Questions