Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pause Flutter Countdown Timer

Tags:

flutter

dart

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")
          ],
        ));
  }
}
like image 720
Zeusox Avatar asked Dec 11 '22 03:12

Zeusox


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

like image 102
Tim Traversy Avatar answered Jan 19 '23 06:01

Tim Traversy