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. I have looked into their documentations, but their is not much about their Timer class...

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

4 Answers

There is no built-in pause function, since the Timer class is mainly intended for scheduling blocks of code for later.

What is your use case? The Stopwatch class has pause and resume funtionality.

I just uploaded this package to implement exactly this:

// 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.

2

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest