What is a Timer in Flutter
In Flutter, a Timer is a class that can be used to schedule a single callback in the future. The callback can be executed at a specific time, or after a specific duration has elapsed. The Timer class is part of the dart:async library and is typically used to perform tasks such as updating the UI, sending network requests, or running animations.
The basic usage of a Timer in Flutter is to create an instance of the Timer class, passing in the duration and callback function as arguments. The callback function will be executed after the specified duration has elapsed.
Here’s an example of how you can use a Timer to update the text of a Text widget every second:
import 'dart:async';
String _timeString = "";
late Timer _timer;
@override
void initState() {
_timer = Timer.periodic(Duration(seconds: 1), (timer) {
setState(() {
_timeString = DateTime.now().toString();
});
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(_timeString)
],
),
),
);
}
![flutter timer](https://flutterassets.com/wp-content/uploads/2023/01/flutter_timer.jpg)
In this example, we create an instance of Timer.periodic passing in a duration of 1 second and a callback function. This callback function updates the _timeString variable to the current time and triggers a rebuild of the widget, which updates the text of the Text widget to show the current time.
It’s important to note that Timers are not guaranteed to execute at exactly the specified interval. The actual time between executions may be longer due to platform limitations and other factors.
It’s also important to cancel the timer when it’s no longer needed. you can use cancel
method on the timer object to cancel the timer.
What is a countdown Timer?
A count-down timer is a timer that counts down from a specified initial value to zero. It is typically used for measuring the duration of an event or for providing a visual indication of the time remaining for a certain action to occur.
It’s an application that counts down from an initial value to zero, it can be implemented in different ways, it can use a Timer class, a Stream or a Ticker. It can also use a stateful or a stateless widget.
In general, it starts with a specified duration, usually in seconds, and counts down to zero, updating the user interface with the remaining time. Once the countdown reaches zero, the timer can be stopped or reset to start over again.
It is widely used in countdown timer apps, alarm clock, stopwatch, and many other apps that need to measure time or count time down.
How to build a countdown Timer in Flutter
To build a countdown timer in Flutter, you can use the Timer.periodic
method to schedule a callback function that updates a variable representing the remaining time, and then use this variable to display the remaining time in a Text
widget. Here’s an example:
import 'dart:async';
int _remainingTime = 10; //initial time in seconds
late Timer _timer;
@override
void initState() {
_startTimer();
super.initState();
}
void _startTimer() {
_timer = Timer.periodic(Duration(seconds: 1), (timer) {
setState(() {
if (_remainingTime > 0) {
_remainingTime--;
} else {
_timer.cancel();
}
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text("Remaining time: $_remainingTime seconds")
],
),
),
);
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
![flutter timer countdown](https://flutterassets.com/wp-content/uploads/2023/01/flutter_timer_countdown.jpg)
In this example, we create an instance of Timer.periodic
passing in a duration of 1 second and a callback function that decrements the _remainingTime
variable. If the _remainingTime
variable is greater than 0, it decrement it by 1 and triggers a rebuild of the widget, which updates the text of the Text widget to show the remaining time.
When the _remainingTime
variable reaches 0, the callback function cancels the timer and stops the countdown.
It’s important to cancel the timer when the widget is no longer needed, so we added the dispose
method to cancel the timer when the widget is removed from the tree.
You can also add more functionality like showing minutes and seconds separately, showing a visual representation of the time remaining, or triggering an event when the countdown is complete.
Start button for countdown Timer in Flutter
To add a button to start the timer in the example I provided earlier, you can simply wrap the Text widget in a Column widget and add a RaisedButton widget to start the timer. Here’s an example:
import 'dart:async';
int _remainingTime = 10; //initial time in seconds
late Timer _timer;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text("Remaining time: $_remainingTime seconds"),
ElevatedButton(
child: Text("Start Timer"),
onPressed: _startTimer,
),
],
),
),
);
}
void _startTimer() {
setState(() {
_remainingTime = 10;
});
_timer = Timer.periodic(Duration(seconds: 1), (timer) {
setState(() {
if (_remainingTime > 0) {
_remainingTime--;
} else {
_timer.cancel();
}
});
});
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
![flutter countdown start button](https://flutterassets.com/wp-content/uploads/2023/01/flutter_countdown_start_button.jpg)
In this example, we added a ElevatedButton
widget to the Column widget and set its onPressed
property to the _startTimer
method. When the button is pressed, the _startTimer
method will be called and it will start the timer.
We also added a setState to reset the _remainingTime to the initial value (10 seconds) before starting the timer.
Countdown stop button in Flutter
You can also add a button to stop the timer, and you can do it by adding a ElevatedButton
and set its onPressed
property to the _timer.cancel()
method.
ElevatedButton(
child: Text("Stop Timer"),
onPressed: _timer.cancel,
),
Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text("Remaining time: $_remainingTime seconds"),
ElevatedButton(
child: Text("Start Timer"),
onPressed: _startTimer,
),
ElevatedButton(
child: Text("Stop Timer"),
onPressed: _timer.cancel,
),
],
),
![flutter countdown start stop button](https://flutterassets.com/wp-content/uploads/2023/01/flutter_countdown_start_stop_button.jpg)
This way, when the user presses the stop button, the timer will be cancelled and the remaining time will stop.
Flutter Timer counts too Fast?
It’s also important to note that if the user presses the button multiple times in a row, the timer will restart and will be running multiple instances of the timer at the same time. To prevent this, you can use_timer?.cancel()
before starting a new Timer, this way the previous timer will be cancelled before starting the new timer.
void _startTimer() {
_timer?.cancel();
setState(() {
_remainingTime = 10;
});
_timer = Timer.periodic(Duration(seconds: 1), (timer) {
setState(() {
if (_remainingTime > 0) {
_remainingTime--;
} else {
_timer.cancel();
}
});
});
}
This way, the previous timer will be cancelled before starting the new timer. By doing this, you are ensuring that only one timer is running at a time,
Flutter countdown Timer with start-stop and cancel buttons
To change the start button to a start/stop button and add a cancel button, you can add a new variable _isRunning
to keep track of the timer’s state, and update the text and onPressed properties of the button accordingly. Here’s an example:
import 'dart:async';
int _remainingTime = 10; //initial time in seconds
late Timer _timer;
bool _isRunning = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text("Remaining time: $_remainingTime seconds"),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
child: Text(_isRunning ? "Stop" : "Start"),
onPressed: _isRunning ? _stopTimer : _startTimer,
),
SizedBox(width: 8),
ElevatedButton(
child: Text("Cancel"),
onPressed: _cancelTimer,
),
],
),
],
),
),
);
}
void _startTimer() {
setState(() {
_remainingTime = 10;
_isRunning = true;
});
_timer = Timer.periodic(Duration(seconds: 1), (timer) {
setState(() {
if (_remainingTime > 0) {
_remainingTime--;
} else {
_timer.cancel();
_isRunning = false;
}
});
});
}
void _stopTimer() {
setState(() {
_isRunning = false;
});
_timer.cancel();
}
void _cancelTimer() {
setState(() {
_isRunning = false;
_remainingTime = 10;
});
_timer.cancel();
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
![flutter countdown start cancel button](https://flutterassets.com/wp-content/uploads/2023/01/flutter_countdown_start_cancel_button.jpg)
![flutter countdown stop cancel button](https://flutterassets.com/wp-content/uploads/2023/01/flutter_countdown_stop_cancel_button.jpg)
In this example, we added a new variable _isRunning
to keep track of the timer’s state, and used it to change the text of the button and the function called on press. We also added a new function _stopTimer
that stops the timer and a new function _cancelTimer
that cancels the timer and resets the remaining time to the initial value.
You can also add some visual feedback to indicate that the timer is running, such as showing a loading animation or disabling the start/stop button while the timer is running.
Also, you can change the text of the button according to the timer state by using the ternary operator instead of the if statement inside the button widget.
ElevatedButton(
child: Text(_isRunning ? "Stop" : "Start"),
onPressed: _isRunning ? _stopTimer : _startTimer,
),
This way, the text of the button will change according to the timer state.
What is a count-up Timer?
A count-up timer is a timer that counts up from zero to a specified final value. It is typically used for measuring the duration of an event or for providing a visual indication of the time elapsed since a certain action occurred.
It’s an application that counts up from zero to a final value, it can be implemented in different ways, it can use a Timer class, a Stream or a Ticker. It can also use a stateful or a stateless widget.
In general, it starts from zero and counts up to a final value, updating the user interface with the elapsed time. Once the count-up reaches the final value, the timer can be stopped or reset to start over again.
It is widely used in stopwatch apps, time tracking, time logging, and many other apps that need to measure time or count time up.
Countup Timer in Flutter
A count-up timer and a count-down timer have a similar structure, the main difference is that the count-up timer increases the value of the timer while the count-down timer decreases it.
Here is an example of how to create a simple count-up timer in Flutter:
import 'dart:async';
int _elapsedTime = 0;
late Timer _timer;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text("Elapsed Time: $_elapsedTime"),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
child: Text("Start"),
onPressed: _startTimer,
),
SizedBox(width: 8),
ElevatedButton(
child: Text("Stop"),
onPressed: _stopTimer,
),
SizedBox(width: 8),
ElevatedButton(
child: Text("Reset"),
onPressed: _resetTimer,
),
],
),
],
),
),
);
}
void _startTimer() {
_timer = Timer.periodic(Duration(seconds: 1), (timer) {
setState(() {
_elapsedTime++;
});
});
}
void _stopTimer() {
_timer.cancel();
}
void _resetTimer() {
_timer.cancel();
setState(() {
_elapsedTime = 0;
});
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
![flutter countup timer](https://flutterassets.com/wp-content/uploads/2023/01/flutter_countup_timer.jpg)
In this example, we used a Timer
object to increase the value of the timer every second, and we added three buttons, one to start the timer, one to stop it, and one to reset it.
As you can see the structure is very similar to the count-down timer, the main difference is that in the callback of the timer, we increment the _elapsedTime value by one, instead of decrementing it.
Also, it’s important to cancel the timer when the widget is no longer needed, so we added the dispose
method to cancel the timer when the widget is removed from the tree.
What is a stopwatch
A stopwatch is a timer that can be started, stopped, and reset to zero, it’s a timer that keeps track of the time elapsed from the moment it is started until the moment it is stopped. It is typically used for measuring the duration of an event or for providing a visual indication of the time elapsed since a certain action occurred.
It’s an application that measures time in a continuous manner and allows the user to start, stop and reset the timer. It can be implemented in different ways, it can use a Timer class, a Stream or a Ticker. It can also use a stateful or a stateless widget.
In general, it starts counting time as soon as it is started and stops counting time as soon as it is stopped, it allows the user to measure the elapsed time between two points in time. Also, it can reset the time to zero to use it again.
It is widely used in sports, timing, and many other areas that need to measure time with a high degree of precision.
How to build a simple stopwatch in Flutter
Here’s an example of how to create a simple stopwatch in Flutter:
import 'dart:async';
Stopwatch _stopwatch = Stopwatch();
late Timer _timer;
String _elapsedTime = "00:00:00.00";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text("Elapsed Time: $_elapsedTime"),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
child: Text("Start"),
onPressed: _startStopwatch,
),
SizedBox(width: 8),
ElevatedButton(
child: Text("Stop"),
onPressed: _stopStopwatch,
),
SizedBox(width: 8),
ElevatedButton(
child: Text("Reset"),
onPressed: _resetStopwatch,
),
],
),
],
),
),
);
}
void _startStopwatch() {
_stopwatch.start();
_timer = Timer.periodic(Duration(milliseconds: 1), (timer) {
setState(() {
_elapsedTime = _stopwatch.elapsed.toString().substring(0, 8);
});
});
}
void _stopStopwatch() {
_stopwatch.stop();
_timer.cancel();
}
void _resetStopwatch() {
_stopwatch.reset();
_timer.cancel();
setState(() {
_elapsedTime = "00:00:00.00";
});
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
![flutter stopwatch example](https://flutterassets.com/wp-content/uploads/2023/01/flutter_stopwatch_example.jpg)
In this example, we used a Stopwatch
object to keep track of the elapsed time, and a Timer
object to update the elapsed time displayed on the screen. The _startStopwatch
method starts the stopwatch and the timer, the _stopStopwatch
method stops the stopwatch and the timer, and the _resetStopwatch
method resets the stopwatch and the timer and sets the elapsed time to “00:00:00.00”.
We also added three buttons, one to start the stopwatch, one to stop it, and one to reset it.
Also, you can use the _stopwatch.elapsedMilliseconds
instead of _stopwatch.elapsed
to get the elapsed time in milliseconds.
It’s important to cancel the timer when the widget is no longer needed, so we added the dispose
method to cancel the timer when the widget is removed from the tree.