首页 > 解决方案 > 我如何在颤动中暂停和恢复 quiver.async CountdownTimer

问题描述

我正在尝试在颤振中实现倒数计时器。我让它工作但无法实现类的暂停和恢复功能。以下是我尝试过的:

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

      }

然而,问题是只有 Pause 有效,而 Resume 无效。请知道如何通过单击按钮使暂停和恢复工作。谢谢

标签: flutterdart

解决方案


sub.resume()不起作用,因为暂停后计时器onData不会触发。您可以像这样简单地制作一个FlatButton并实现。onTap

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();

推荐阅读