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.
Table of Contents
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:
- 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.
- timerText Getter: Computes and returns a string representation of the timer in
mm:ss
format. - 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 thecurrentSeconds
and cancels the timer if the maximum time is reached. - initState() Method: Invoked when the stateful widget is inserted into the tree. It starts the timer when the widget is initialized.
- 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:
- Implement the Widget: Place the
GenericTimer
widget where you want the timer to appear within your app’s UI. - 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.
- 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:
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 ofcurrentSeconds
.
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.