How To Create Our Own Flutter Timer [Step By Step Guide]

flutter timer

In this tutorial, we’ll learn the creation of custom Flutter timer(specify time, start, stop and reset). We’ll use a practical Flutter example with step by step explanation for better understanding.

Introduction: Custom Flutter Timer

flutter custom timer

We’ll be creating our own timer in Flutter. In this timer, we’ll be able to set a specific time, start, stop and reset it. We highly recommend you to follow the guide step by step to better understand how to implement it. So let’s not keep ourselves waiting anymore and get right into it.

Creating Our Own Flutter Timer (Step By Step Explanation)

Follow below steps for complete guide.

Step 1: Import Timer

First we’ve to import the timer so we can use its method. See below:

import 'dart:async';

We’ve to import it in the dart file where we want to use the timer.

Timer? timer;
We can then use the timer class like this. In our code, we’ll be using its periodic method. This method can be used to repeatedly call/run a function with a specific duration. See below code:
timer=Timer.periodic(duration,function)

In order to stop the timer, we can use its cancel method. See below:

timer!.cancel();

Step 2: Create Start, Stop and Reset Buttons

We’ve used Flutter material buttons to start, stop and reset Flutter timer. The complete source code will be provided in the end.

Step 3: Run, Stop and Reset Functions

We’ve created three functions in which logic to start, stop and reset the timer is implemented. Function that’ll start timer has a logic specified in it. This logic will continuously decrement the values(hours, minutes and seconds) until all are set to 0.

Step 4: Select Time(Hours, Minutes or Seconds)

We’ve used Flutter dropdown widgets to select the values of hours, minutes and even seconds. You can use other widgets as well like time picker etc.

Step 5: Display the Flutter Timer

We’ve used Flutter text widget to show the timer on screen.

Test The Timer

Let’s now test our timer. See below images:

flutter timer

custom flutter timer

flutter custom timer

So this is how we can make our own custom Flutter timer. Hope you like this post.

Task Assigned To You

We’ve a task for you. We want you to customize the color of buttons like when the timer starts, then set the color of start button and reset button to grey. Also, enable the stop button. When the timer is stopped, then give a green color to reset button(also enable it) and after resetting, set the color of stop and reset button to grey(disable both of them). Also, make the color of start button to blue if a time is specified(enable it as well).

Do share the code with us. We’ll be very happy to add it to this article.

Feel free to share this post with your developer friends. If you’ve any questions regarding the implementation of timer in Flutter, then feel free to ask it in the comments. We’ll be more than happy to answer all of them.

The complete source code of custom Flutter timer is given in the below section.

Custom Flutter Timer Complete Source Code

import 'dart:async';
import 'package:flutter/material.dart';
void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(debugShowCheckedModeBanner: false, home: HomePage());
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
  @override
  State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {

  Timer? timer;

  List hoursList = [];
  List minutesList = [];
  List secondsList = [];

  String? hoursVal;
  String? minutesVal;
  String? secondsVal;

  int hours = 0;
  int minutes = 0;
  int seconds = 0;

  String displayTime = '00:00:00';

  runTimer() {
    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (seconds > 0) {
        seconds = seconds - 1;
      }
      if (seconds == 0) {
        if (minutes > 0) {
          minutes = minutes - 1;
          seconds = 60;
        }
      }
      if (minutes == 0) {
        if (hours > 0) {
          hours = hours - 1;
          minutes = 60;
        }
      }

      String result =
          '${hours < 10 ? '0' : ''}$hours : ${minutes < 10 ? '0' : ''}$minutes : ${seconds < 10 ? '0' : ''}$seconds';
      displayTime = result;
      setState(() {});
    });
  }

  stopTimerr() {
    timer!.cancel();
    setState(() {});
  }

  resetTimerr() {
    stopTimerr();
    hours = 0;
    minutes = 0;
    seconds = 0;
    hoursVal = '0';
    minutesVal = '0';
    secondsVal = '0';
    displayTime = '00:00:00';
    setState(() {});
  }

  @override
  void initState() {

    for (int i = 0; i < 25; i++) {
      hoursList.add(i.toString());
    }

    for (int i = 0; i < 61; i++) {
      minutesList.add(i.toString());
    }

    for (int i = 0; i < 61; i++) {
      secondsList.add(i.toString());
    }

    setState(() {});
    super.initState();
  }

  @override
  void dispose(){
  stopTimerr();
  super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SizedBox(
      height: double.infinity,
      width: double.infinity,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          
          // It will display the Flutter timer
          Text(
            displayTime,
            style: TextStyle(
              color: timer == null ? Colors.grey : Colors.blue,
              fontSize: 60,
            ),
          ),

          SizedBox(
            height: 20,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [

              Column(
                children: [
                  Text(
                    'Hours',
                    style: TextStyle(
                        color: Colors.grey.shade600,
                        fontSize: 15,
                        fontWeight: FontWeight.w500),
                  ),
                  Container(
                    width: 70,
                    height: 35,
                    margin: EdgeInsets.only(top: 5),
                    padding: EdgeInsets.symmetric(horizontal: 10),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(5),
                        border: Border.all(color: Colors.grey, width: .5)),
                    child: DropdownButtonHideUnderline(
                      child: DropdownButton(
                          icon: Icon(
                            Icons.keyboard_arrow_down_sharp,
                            size: 18,
                            color: Colors.grey,
                          ),
                          isExpanded: true,
                          hint: Text(
                            'Select',
                            style: TextStyle(
                              color: Colors.grey,
                              fontSize: 13,
                            ),
                          ),
                          value: hoursVal,
                          items: [
                            for (int i = 0; i < hoursList.length; i++)
                              DropdownMenuItem(
                                  value: hoursList[i],
                                  child: Text(hoursList[i].toString(),
                                      style: TextStyle(
                                          fontSize: 16,
                                          color: Colors.grey.shade600))),
                          ],
                          onChanged: (val) {
                            setState(() {
                              hoursVal = val.toString();
                              hours = int.parse(hoursVal!);
                            });
                          }),
                    ),
                  ),
                ],
              ),

              Column(
                children: [
                  Text(
                    'Minutes',
                    style: TextStyle(
                        color: Colors.grey.shade600,
                        fontSize: 15,
                        fontWeight: FontWeight.w500),
                  ),
                  Container(
                    width: 70,
                    height: 35,
                    margin: EdgeInsets.only(top: 5),
                    padding: EdgeInsets.symmetric(horizontal: 10),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(5),
                        border: Border.all(color: Colors.grey, width: .5)),
                    child: DropdownButtonHideUnderline(
                      child: DropdownButton(
                          icon: Icon(
                            Icons.keyboard_arrow_down_sharp,
                            size: 18,
                            color: Colors.grey,
                          ),
                          isExpanded: true,
                          hint: Text(
                            'Select',
                            style: TextStyle(
                              color: Colors.grey,
                              fontSize: 13,
                            ),
                          ),
                          value: minutesVal,
                          items: [
                            for (int i = 0; i < minutesList.length; i++)
                              DropdownMenuItem(
                                  value: minutesList[i],
                                  child: Text(minutesList[i].toString(),
                                      style: TextStyle(
                                          fontSize: 16,
                                          color: Colors.grey.shade600))),
                          ],
                          onChanged: (val) {
                            setState(() {
                              minutesVal = val.toString();
                              minutes = int.parse(minutesVal!);
                            });
                          }),
                    ),
                  ),
                ],
              ),

              Column(
                children: [
                  Text(
                    'Seconds',
                    style: TextStyle(
                        color: Colors.grey.shade600,
                        fontSize: 15,
                        fontWeight: FontWeight.w500),
                  ),
                  Container(
                    width: 70,
                    height: 35,
                    margin: EdgeInsets.only(top: 5),
                    padding: EdgeInsets.symmetric(horizontal: 10),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(5),
                        border: Border.all(color: Colors.grey, width: .5)),
                    child: DropdownButtonHideUnderline(
                      child: DropdownButton(
                          icon: Icon(
                            Icons.keyboard_arrow_down_sharp,
                            size: 18,
                            color: Colors.grey,
                          ),
                          isExpanded: true,
                          hint: Text(
                            'Select',
                            style: TextStyle(
                              color: Colors.grey,
                              fontSize: 13,
                            ),
                          ),
                          value: secondsVal,
                          items: [
                            for (int i = 0; i < secondsList.length; i++)
                              DropdownMenuItem(
                                  value: secondsList[i],
                                  child: Text(secondsList[i].toString(),
                                      style: TextStyle(
                                          fontSize: 16,
                                          color: Colors.grey.shade600))),
                          ],
                          onChanged: (val) {
                            setState(() {
                              secondsVal = val.toString();
                              seconds = int.parse(secondsVal!);
                            });
                          }),
                    ),
                  ),
                ],
              ),
            ],
          ),

          Padding(
            padding: EdgeInsets.only(top: 20, bottom: 10),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                MaterialButton(
                  onPressed: (hours == 0 && minutes == 0 && seconds == 0)
                      ? null
                      : stopTimerr,
                  disabledColor: Colors.grey,
                  disabledTextColor: Colors.white60,
                  textColor: Colors.white,
                  color: Colors.red.shade600,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10)),
                  child: Text(
                    'Stop',
                    style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
                  ),
                ),

                MaterialButton(
                  onPressed: (hours == 0 && minutes == 0 && seconds == 0)
                      ? null
                      : resetTimerr,
                  disabledColor: Colors.grey,
                  disabledTextColor: Colors.white60,
                  color: Colors.green.shade600,
                  textColor: Colors.white,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10)),
                  child: Text(
                    'Reset',
                    style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
                  ),
                )
              ],
            ),
          ),

          Padding(
            padding: EdgeInsets.symmetric(horizontal: 20),
            child: MaterialButton(
              onPressed: (hours == 0 && minutes == 0 && seconds == 0)
                  ? null
                  : () {
                      if (timer != null) {
                        stopTimerr();
                      }
                      runTimer();
                    },
              color: Colors.blue.shade600,
              height: 50,
              disabledColor: Colors.grey,
              disabledTextColor: Colors.white60,
              textColor: Colors.white,
              minWidth: double.infinity,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10)),
              child: Text(
                'Start',
                style: TextStyle(
                  fontSize: 17,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ),
        ],
      ),
    ));
  }
}

Conclusion

To conclude this tutorial, hope you now have an in-depth knowledge of how to create custom Flutter timer. We’ll be looking forward to receive your informative thoughts on this post.

We’d also love to see you visit our other tutorials on Flutter app development. Thank you for reading this article.

Leave a Comment

Your email address will not be published. Required fields are marked *