暂停Flutter倒计时计时器

6

我一直在使用Dart计时器类进行开发,目前已经可以基本实现它的功能,但是我卡在尝试添加暂停功能上。我查看了他们的文档,但是关于计时器类的内容并不多...

是否有办法在单击时暂停和恢复计时器/倒计时?这是我目前已经实现的:

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")
          ],
        ));
  }
}
4个回答

11

由于 Timer 类主要用于计划以后的代码块,因此没有内置的 pause 函数。

您的用例是什么?Stopwatch 类具有暂停和恢复功能。


8

在我的情况下,我希望 timer 每秒运行一次,并在需要时将其冻结,但我意识到您的库仅适用于在特定时间段后使代码运行。 - Opeyemi Sanusi
你只需要在定时器回调函数中使用 timer.reset(); timer.start(); 就可以重新启动它(使其周期性)。以下是一个使用它实现倒计时的示例,与你想要的相同,只是定时器将在一定次数后结束:https://pub.dev/packages/pausable_timer#example-pausable-countdown-implementation - luca

3
以下是包含暂停和震动功能的Flutter示例(源代码):
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"),
            ),
            ],
        ),
        ]));
}
}

2

我们定义的变量: 在页面打开时启动计时器。 当页面关闭时停止计时器。

如果屏幕被触摸,变量“duration”将变为真,并且计时器停止倒计时。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接