How to Show Timer in Flutter?

In mobile app development, it’s common to have a timer in flutter for various purposes such as countdowns, reminders, or any time-based functionalities.

In this blog post, we will explore how to implement a basic timer widget in a Flutter application.

show timer in flutter

Introduction to the Code of Timer in Flutter

Let’s start by examining the provided code:

import 'dart:async';

import 'package:flutter/material.dart';

class GenericTimer extends StatefulWidget {
  @override
  _GenericTimerState createState() => _GenericTimerState();
}

class _GenericTimerState extends State<GenericTimer> {
  final interval = const Duration(seconds: 1);

  final int timerMaxSeconds = 60;

  int currentSeconds = 0;

  String get timerText =>
      '${((timerMaxSeconds - currentSeconds) ~/ 60).toString().padLeft(2, '0')} : ${((timerMaxSeconds - currentSeconds) % 60).toString().padLeft(2, '0')} Sec';

  startTimeout([int? milliseconds]) {
    var duration = interval;
    Timer.periodic(duration, (timer) {
      setState(() {
        currentSeconds = timer.tick;
        if (timer.tick >= timerMaxSeconds) timer.cancel();
      });
    });
  }

  @override
  void initState() {
    startTimeout();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Icon(
          Icons.timer,
          color: Colors.white,
        ),
        SizedBox(
          width: 5,
        ),
        Text(timerText)
      ],
    );
  }
}

Explanation for the Timer in Flutter:

  1. Properties:
    • interval: A constant duration of 1 second, used for the timer.
    • timerMaxSeconds: The maximum duration of the timer, set to 60 seconds.
    • currentSeconds: Tracks the current elapsed time in seconds.
  2. timerText Getter: Computes and returns a string representation of the timer in mm:ss format.
  3. startTimeout() Method: Starts the timer. It uses Timer.periodic to repeatedly execute a callback function at the specified interval (interval). Inside the callback, it updates the currentSeconds and cancels the timer if the maximum time is reached.
  4. initState() Method: Invoked when the stateful widget is inserted into the tree. It starts the timer when the widget is initialized.
  5. build() Method: Constructs and returns the widget tree. It displays an icon (timer) and the timer text in a row layout.

Implementing the Timer in Flutter

To utilize the GenericTimer widget in your Flutter application, follow these steps:

  1. Implement the Widget: Place the GenericTimer widget where you want the timer to appear within your app’s UI.
  2. Customize: Customize the appearance and behavior of the timer as needed. You can adjust properties such as colors, font sizes, and maximum timer duration according to your application’s requirements.
  3. Handle Timer Expiry: Implement logic to handle what happens when the timer expires. Depending on your use case, you may want to perform certain actions or trigger events when the timer reaches its maximum duration.

Core Concept of the Code

1. timerMaxSeconds:

This variable stores the maximum duration of the timer in seconds. In this case, it’s set to 60 seconds.

2. currentSeconds:

This variable keeps track of the elapsed time in seconds. Initially set to 0, it will be incremented as the timer progresses.

3. timerText getter:

This getter method returns a string representing the timer text to be displayed. It calculates the remaining minutes and seconds based on the difference between timerMaxSeconds and currentSeconds. The padLeft function is used to ensure that the minutes and seconds are always displayed as two digits.

4. startTimeout() function:

This function starts the timer. It is used Timer.periodic to repeatedly execute a callback function at a specified interval (duration). Inside the callback function, currentSeconds is updated with timer.tick, which represents the number of ticks (iterations) since the timer started. If the number of ticks exceeds or equals timerMaxSeconds, the timer is canceled using timer.cancel().

Output:

output of  Timer in Flutter

Additional Notes:

  • Timer.periodic is a method that repeatedly calls a function with a specified time interval.
  • setState() is called inside the timer callback to update the UI with the new value of currentSeconds.

Also Read:

Conclusion

In this blog post, we’ve explored how to implement a basic timer widget in a Flutter application. The GenericTimer widget provides a flexible and reusable way to display timers for various purposes within your app.

If you haven’t already installed Flutter, you can follow the official: Flutter Installation Guide. to set it up.

Share:
Ambika Dulal

Ambika Dulal is a Flutter Developer from Nepal who is passionate about building beautiful and user-friendly apps. She is always looking for new challenges and is eager to learn new things. She is also a strong believer in giving back to the community and is always willing to help others.

Leave a Comment

AO Logo

App Override is a leading mobile app development company based in Kathmandu, Nepal. Specializing in both Android and iOS app development, the company has established a strong reputation for delivering high-quality and innovative mobile solutions to clients across a range of industries.

Services

UI/UX Design

Custom App Development

Mobile Strategy Consulting

App Testing and Quality Assurance

App Maintenance and Support

App Marketing and Promotion

Contact

App Override

New Plaza, Kathmandu