flutter - 如何在Flutter中暂停和恢复quiver.async CountdownTimer

标签 flutter dart

我试图在 flutter 中实现倒数计时器。我可以使用它,但是无法实现该类的“暂停和继续”功能。以下是我尝试过的方法:

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

      }

但是,问题在于只有“暂停”有效,而“简历”无效。请任何想法如何通过单击按钮使“暂停”和“继续”工作。
谢谢

最佳答案

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

关于flutter - 如何在Flutter中暂停和恢复quiver.async CountdownTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61359220/

相关文章:

string - 如何在 Dart 中获取字符串的字节?

javascript - Flutter中是否可以使用JS可视化库(例如Chart.js或D3.js)?

firebase - 从现有的云函数 Flutter 项目开始

flutter - 从单独的Dart文件导入Flutter小部件是否要昂贵得多?

flutter - 以井号 (#) 为前缀的符号在 Dart 代码中有什么作用?

flutter - 有没有办法让多个 FutureBuilder 从 ChangeNotifier 使用同一个 future ?

dart - 英雄动画在嵌套导航器中不起作用

flutter - 如何在 Dart 中将代码迁移到空安全

ios - Flutter check if app was in memory when launched (How to check if splash screen is shown in iOS)

webgl - 从 ImageElement 加载获取 Future