简体   繁体   English

暂停颤振倒数计时器

[英]Pause Flutter Countdown Timer

I have been playing with Dart Timer Class that I got it to work in its very basic form, however I am stuck trying to add a pause function to it.我一直在玩 Dart Timer Class,我让它以非常基本的形式工作,但是我试图向它添加暂停功能。 I have looked into their documentations, but their is not much about their Timer class...我查看了他们的文档,但他们对 Timer 类的了解并不多......

Is there any way I can pause and resume the timer/countdown on click?有什么办法可以在点击时暂停和恢复计时器/倒计时? This is what I have achieved so far:这是我迄今为止取得的成就:

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}


class _MyHomePageState extends State<MyHomePage> {

  Timer _timer;
  int _start = 10;

  void startTimer() {
    const oneSec = const Duration(seconds: 1);
    _timer = new Timer.periodic(
        oneSec,
            (Timer timer) => setState(() {
          if (_start < 1) {
            timer.cancel();
          } else {
            _start = _start - 1;
          }
        }));
  }


  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: AppBar(title: Text("Timer test")),
        body: Column(
          children: <Widget>[
            RaisedButton(
              onPressed: () {
                startTimer();
              },
              child: Text("start"),
            ),
            Text("$_start")
          ],
        ));
  }
}

There is no built-in pause function, since the Timer class is mainly intended for scheduling blocks of code for later.没有内置的pause功能,因为Timer类主要用于为以后调度代码块。

What is your use case?你的用例是什么? The Stopwatch class has pause and resume funtionality. Stopwatch类具有暂停和恢复功能。

Working flutter example with pause and vibrations is below ( source )带有暂停和振动的工作颤振示例如下( 来源

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

void main() => runApp(MaterialApp(home: CountdownCard()));

class CountdownCard extends StatefulWidget {
// This widget is the root of your application.

@override
_CountdownCardState createState() => _CountdownCardState();
}

class _CountdownCardState extends State<CountdownCard> {
Timer _timer;
int _start = 0;
bool _vibrationActive = false;

void startTimer(int timerDuration) {
    if (_timer != null) {
    _timer.cancel();
    cancelVibrate();
    }
    setState(() {
    _start = timerDuration;
    });
    const oneSec = const Duration(seconds: 1);
    print('test');
    _timer = new Timer.periodic(
    oneSec,
    (Timer timer) => setState(
        () {
        if (_start < 1) {
            timer.cancel();
            print('alarm');
            vibrate();
        } else {
            _start = _start - 1;
        }
        },
    ),
    );
}

void cancelVibrate() {
    _vibrationActive = false;
    Vibration.cancel();
}

void vibrate() async {
    _vibrationActive = true;
    if (await Vibration.hasVibrator()) {
    while (_vibrationActive) {
        Vibration.vibrate(duration: 1000);
        await Future.delayed(Duration(seconds: 2));
    }
    }
}

void pauseTimer() {
    if (_timer != null) _timer.cancel();
}

void unpauseTimer() => startTimer(_start);

@override
void dispose() {
    _timer.cancel();
    super.dispose();
}

@override
Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
        title: Text('Countdown'),
        ),
        body: Wrap(children: <Widget>[
        Column(
            children: <Widget>[
            RaisedButton(
                onPressed: () {
                startTimer(10);
                },
                child: Text("start"),
            ),
            Text("$_start"),
            RaisedButton(
                onPressed: () {
                pauseTimer();
                },
                child: Text("pause"),
            ),
            RaisedButton(
                onPressed: () {
                unpauseTimer();
                },
                child: Text("unpause"),
            ),
            RaisedButton(
                onPressed: () {
                cancelVibrate();
                },
                child: Text("stop alarm"),
            ),
            ],
        ),
        ]));
}
}

I just uploaded this package to implement exactly this: https://pub.dev/packages/pausable_timer我刚刚上传了这个包来实现这个: https : //pub.dev/packages/pausable_timer

// It starts paused
final timer = PausableTimer(Duration(seconds: 1), () => print('Fired!'));
timer.start();
timer.pause();
timer.start();

There is also an issue requesting the feature in Dart itself , but it doesn't look like it will be added soon. Dart 本身也存在请求该功能问题,但看起来不会很快添加。

variables we define start timer on page opening.我们在页面打开时定义启动计时器的变量。 timer off when page is closed.页面关闭时计时器关闭。

if the screen is touched, the variable duration becomes true and the timer stops counting down如果触摸屏幕,可变持续时间变为真,计时器停止倒计时

     Timer? _timer;
     int _start = 200;
     bool duration = false;
     Duration oneSec = const Duration(milliseconds: 10);
    

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    startTimer();
  }

  @override
  void dispose() {
    _timer!.cancel();
    super.dispose();
  }

 ```
    GestureDetector(
              onTap: () {},
              onTapDown: (e) {
                setState(() {
                  duration = true;
                });
              },
              onHorizontalDragEnd: (e) {
                Navigator.pop(context);
              },
              onTapUp: (e) {
                setState(() {
                  duration = false;
                });
              },
              child:Text("demo page")}
  void startTimer() {
    _timer = new Timer.periodic(
      oneSec,
      (Timer timer) {
        if (_start == 0) {
          setState(() {
            timer.cancel();
            Navigator.pop(context);
          });
        } else {
          setState(() {
            duration == false ? _start-- : null;
          });
        }
      },
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM