Timer Flutter : How to countdown starts and ends

Flutter has a Timer class that we can configure. As a result, we can either start it, stop it or resume it.

When a timer in flutter works it actually starts a countdown. As we know, in many cases, we need a timer to start a countdown in a flutter app.

We can see a simple code of Timer class in flutter.

void main() {
  timeOut(3 * 1000); // 3 seconds.
}

Timer timeOut([int milliseconds = 10000]) =>
    Timer(Duration(milliseconds: milliseconds), callTimeout);

void callTimeout() {  // callback function which we can use later
  Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => const FinalDEstination(),
          ),
        );
}

But in reality, we use a very handy plugin that gives us the same opportunity with many built-in features that we can use.

The plugin or package “circular countdown timer” helps us to achieve the same goal. As an outcome we can start a countdown, and as it ends, we can start our flutter app.

Let’s see how it looks and starts its journey. In addition it will also give us an idea about the plugin.

Timer Flutter countdown starts
Timer Flutter countdown starts

Now we can take a look at the code step by step.

The top level function main() runs the flutter app. 

import 'package:flutter/material.dart';
import 'view/count_down_timer_app.dart';

void main() => runApp(const CountDownTimerApp());

// flutter run -d chrome --web-renderer html

Next, the count down timer app is a simple material app widget that uses a light theme. 

To test in your own machine, you may change it to a dark theme.

Meanwhile we want another stateful widget that will handle the plugin. However, to use the plugin, firstly, we need to add the dependency in our pubspec.yaml file.

dependencies:
  animations: ^2.0.2
  cupertino_icons: ^1.0.2
  flutter:
    sdk: flutter
  google_fonts: ^2.2.0
  material_design_icons_flutter: ^5.0.6595  
  circular_countdown_timer: ^0.2.0

The stateful widget “show circular countdown” timer needs two variables. 

The parameter “controller” of the plugin plays the most important role.

Why? 

Because it starts, pauses, resumes the timer. 

Therefore, we need to create a new controller object and passes that as a constructor parameter.

import 'package:flutter/material.dart';
import 'package:circular_countdown_timer/circular_countdown_timer.dart';
import 'package:google_fonts/google_fonts.dart';

import 'circular_count_down_timer_widget.dart';

class ShowCircularCountDownTimer extends StatefulWidget {
  const ShowCircularCountDownTimer({Key? key}) : super(key: key);

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

class _ShowCircularCountDownTimerState extends State {
  final CountDownController _countDownController = CountDownController();

  bool _isPaused = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'Count Down Begins...',
          style: GoogleFonts.adventPro(
            fontSize: 35.0,
            fontWeight: FontWeight.bold,
            color: Colors.yellow,
          ),
        ),
        centerTitle: true,
      ),
      body: Center(
        child: CircularCountDownTimerWidget(controller: _countDownController),
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () {
          setState(() {
            if (_isPaused) {
              _isPaused = false;

              _countDownController.resume();
            } else {
              _isPaused = true;

              _countDownController.pause();
            }
          });
        },
        icon: Icon(_isPaused ? Icons.play_arrow : Icons.pause),
        label: Text(
          _isPaused ? 'Resume' : 'Pause',
          style: GoogleFonts.laila(
            fontSize: 25.0,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }
}

As we see in the above code, the controller object controls the animation. However, we can manipulate it with another local boolean variable “_isPaused”.

How the Timer plugin works in Flutter

Besides that, the plugin comes with a lot of other features that we can use to design the look of the timer. 

Let’s see the images first, so we can guess how the timer approaches towards the end of the countdown.

Timer Flutter countdown moves to end point
Timer Flutter countdown moves to end point

As the timer ends, we can start a new page. 

In short, that will add a meaning to our countdown timer app. Whenever we build a flutter app, we want to give users a good experience. Right? 

For that reason, we need to do something which makes sense.

Timer Flutter countdown ends and a new page opens up
Timer Flutter countdown ends and a new page opens up

Let’s see the code now. The circular countdown timer plugin comes with lots of parameters. 

As a result, we can use them as wisely as possible.

import 'package:flutter/material.dart';
import 'package:circular_countdown_timer/circular_countdown_timer.dart';
import 'package:flutter_artisan/view/final_destination.dart';
import 'package:google_fonts/google_fonts.dart';

class CircularCountDownTimerWidget extends StatelessWidget {
  const CircularCountDownTimerWidget({
    Key? key,
    required CountDownController controller,
  })  : _countDownController = controller,
        super(key: key);

  final CountDownController _countDownController;

  @override
  Widget build(BuildContext context) {
    return CircularCountDownTimer(
      width: MediaQuery.of(context).size.width / 2,
      height: MediaQuery.of(context).size.height / 2,
      duration: 5,
      fillColor: Colors.redAccent,
      ringColor: Colors.white38,
      controller: _countDownController,
      backgroundColor: Colors.amber,
      strokeWidth: 10.0,
      strokeCap: StrokeCap.round,
      isTimerTextShown: true,
      isReverse: false,
      onComplete: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => const FinalDEstination(),
          ),
        );
      },
      textStyle: GoogleFonts.aclonica(
        fontSize: 70.0,
        fontWeight: FontWeight.bold,
        color: Colors.red,
      ),
    );
  }
}

Finally, if you want to clone this app and run in your machine, please visit this GitHub repository.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

Courses at Educative

GitHub repository

Technical blog

Twitter

Comments

Leave a Reply