Flutterexperts

Crafting Next-Gen Apps with Flutter Power
Stopwatch Timer In Flutter

Flutter is enormously motivated by React and numerous ideas are now recognizable: stateful/stateless, render function, segment hierarchy, and so on Concerning Dart language which backs Flutter, it acquires various of the best highlights from different dialects while keeping off from the terrible things, so if you definitely know python, JavaScript, C++, you can get Dart rapidly.

In this blog, we will explore the Stopwatch Timer In Flutter. We will see how to implement a demo program of the stopwatch timer and show how to create it in your flutter applications.

Table Of Contents::

Introduction

Code Implement

Code File

Conclusion



Introduction:

The below demo video shows how to create a stopwatch timer in a flutter. It shows how the stopwatch timer will work in your flutter applications. It shows when code successfully runs, then user press the start timer button, then count down timing will be start and the user also press the stop and cancel timer button. It will be shown on your devices.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called stopwatch_timer_page.dart inside the lib folder.

First, we will create a const countdownDuration is equal to Duration was ten minutes and create a variable of duration. We will also create a timer variable and create a bool variable countDown is equal to true.

static const countdownDuration = Duration(minutes: 10);
Duration duration = Duration();
Timer? timer;

bool countDown =true;

We will create an initState() method. In this method, we will add the reset() function. We will define the below code.

@override
void initState() {
// TODO: implement initState
super.initState();
reset();
}

We will define reset() function:

We will create a reset() method. In this method, if countDown is true, then in setState() we will add duration is equal to the countdownDuration. Else, duration is equal to Duration in setState().

void reset(){
if (countDown){
setState(() =>
duration = countdownDuration);
} else{
setState(() =>
duration = Duration());
}
}

Now, we will create a startTimer() function. We will import that dart: async;

import 'dart:async';

We will add a timer variable that is equal to the Timer. periodic add duration was one second and addTime() method. We will define below the code.

void startTimer(){
timer = Timer.periodic(Duration(seconds: 1),(_) => addTime());
}

We will define addTime() method:

In the addTime method, inside we will add the final addSeconds that is equal to the countDown is true then -1 else 1. We will add setState(). Inside, final seconds that is equal to the duration.inSeconds plus addSeconds. If the second is less than zero then timer. cancel() else, the duration that is equal to the Duration(seconds: seconds).

void addTime(){
final addSeconds = countDown ? -1 : 1;
setState(() {
final seconds = duration.inSeconds + addSeconds;
if (seconds < 0){
timer?.cancel();
} else{
duration = Duration(seconds: seconds);

}
});
}

Now, we will create a stopTimer() method. In this method, if resets that are equal to true then reset() method call. We will add a timer. cancel in the setState method.

void stopTimer({bool resets = true}){
if (resets){
reset();
}
setState(() => timer?.cancel());
}

In the body, we will create Column() widget. In this widget, we will add the mainAxisAlignment was center. Add the buildTime() and buildButtons() widget. We will define below the code.

Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
buildTime(),
SizedBox(height: 80,),
buildButtons()
],
),

We will define buildTime() widget:

In this method, we will create a final hour is equal to the twoDigits(duration.inHours). Add final minutes is equal to the twoDigits(duration.inMinutes.remainder(60)). Add final seconds is equal to the twoDigits(duration.inSeconds.remainder(60)). We will return Row(). Inside, we will add three buildTimeCard() methods and we will be passing arguments time and headers. We will describe the code below.

Widget buildTime(){
String twoDigits(int n) => n.toString().padLeft(2,'0');
final hours =twoDigits(duration.inHours);
final minutes =twoDigits(duration.inMinutes.remainder(60));
final seconds =twoDigits(duration.inSeconds.remainder(60));
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
buildTimeCard(time: hours, header:'HOURS'),
SizedBox(width: 8,),
buildTimeCard(time: minutes, header:'MINUTES'),
SizedBox(width: 8,),
buildTimeCard(time: seconds, header:'SECONDS'),
]
);
}

We will define buildTimeCard() widget:

In this widget, we will be passing two arguments was time and header. We will return Column. Inside, add a container with decoration and its child we will add text was time. We will also add another text was a header.

Widget buildTimeCard({required String time, required String header}) =>
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20)
),
child: Text(
time, style: TextStyle(fontWeight: FontWeight.bold,
color: Colors.black,fontSize: 50),),
),
SizedBox(height: 24,),
Text(header,style: TextStyle(color: Colors.black45)),
],
);

We will define buildButtons() widget:

In this widget, we will add final isRunning is equal to the timer is equal to null then false else timer .isActive. We will add final isCompleted is equal to duration.inSeconds is equal to zero. We will return isRunning || isCompleted then add a Row() widget. Inside, add ButtonWidget class. We will define the below code. Add two buttons were stop and others were canceled. Also, we will add a start timer button.

Widget buildButtons(){
final isRunning = timer == null? false: timer!.isActive;
final isCompleted = duration.inSeconds == 0;
return isRunning || isCompleted
? Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ButtonWidget(
text:'STOP',
onClicked: (){
if (isRunning){
stopTimer(resets: false);
}
}),
SizedBox(width: 12,),
ButtonWidget(
text: "CANCEL",
onClicked: stopTimer
),
],
)
: ButtonWidget(
text: "Start Timer!",
color: Colors.black,
backgroundColor: Colors.white,
onClicked: (){
startTimer();
});

}

We will define ButtonWidget class:

In this class, we will create an ElevatedButton(). Inside, we will add onPressed method, text.

import 'package:flutter/material.dart';

class ButtonWidget extends StatelessWidget {
final String text;
final Color color;
final Color backgroundColor;
final VoidCallback onClicked;

const ButtonWidget({Key? key, required this.text, required this.onClicked,
this.color = Colors.white, this.backgroundColor = Colors.black}) : super(key: key);
@override
Widget build(BuildContext context) => ElevatedButton(
style: ElevatedButton.styleFrom(
primary: backgroundColor,
padding: EdgeInsets.symmetric(horizontal: 32, vertical: 16)
),
onPressed: onClicked,
child: Text(text,style: TextStyle(fontSize: 20,color: color),)
);

}

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Final Output

Code File:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_stopwatch_timer_demo/button_widget.dart';

class StopWatchTimerPage extends StatefulWidget {
@override
_StopWatchTimerPageState createState() => _StopWatchTimerPageState();
}

class _StopWatchTimerPageState extends State<StopWatchTimerPage> {
static const countdownDuration = Duration(minutes: 10);
Duration duration = Duration();
Timer? timer;

bool countDown =true;

@override
void initState() {
// TODO: implement initState
super.initState();
reset();
}

void reset(){
if (countDown){
setState(() =>
duration = countdownDuration);
} else{
setState(() =>
duration = Duration());
}
}

void startTimer(){
timer = Timer.periodic(Duration(seconds: 1),(_) => addTime());
}

void addTime(){
final addSeconds = countDown ? -1 : 1;
setState(() {
final seconds = duration.inSeconds + addSeconds;
if (seconds < 0){
timer?.cancel();
} else{
duration = Duration(seconds: seconds);

}
});
}

void stopTimer({bool resets = true}){
if (resets){
reset();
}
setState(() => timer?.cancel());
}

@override
Widget build(BuildContext context) => Scaffold(
backgroundColor: Colors.orange[50],
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text("Flutter StopWatch Timer Demo"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
buildTime(),
SizedBox(height: 80,),
buildButtons()
],
),
),
);

Widget buildTime(){
String twoDigits(int n) => n.toString().padLeft(2,'0');
final hours =twoDigits(duration.inHours);
final minutes =twoDigits(duration.inMinutes.remainder(60));
final seconds =twoDigits(duration.inSeconds.remainder(60));
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
buildTimeCard(time: hours, header:'HOURS'),
SizedBox(width: 8,),
buildTimeCard(time: minutes, header:'MINUTES'),
SizedBox(width: 8,),
buildTimeCard(time: seconds, header:'SECONDS'),
]
);
}

Widget buildTimeCard({required String time, required String header}) =>
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20)
),
child: Text(
time, style: TextStyle(fontWeight: FontWeight.bold,
color: Colors.black,fontSize: 50),),
),
SizedBox(height: 24,),
Text(header,style: TextStyle(color: Colors.black45)),
],
);

Widget buildButtons(){
final isRunning = timer == null? false: timer!.isActive;
final isCompleted = duration.inSeconds == 0;
return isRunning || isCompleted
? Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ButtonWidget(
text:'STOP',
onClicked: (){
if (isRunning){
stopTimer(resets: false);
}
}),
SizedBox(width: 12,),
ButtonWidget(
text: "CANCEL",
onClicked: stopTimer
),
],
)
: ButtonWidget(
text: "Start Timer!",
color: Colors.black,
backgroundColor: Colors.white,
onClicked: (){
startTimer();
});

}
}

Conclusion:

In the article, I have explained the basic structure of the Stopwatch Timer in a flutter; you can modify this code according to your choice. This was a small introduction to Shimmer Animation Effect On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying up the Stopwatch Timer in your flutter projectsWe will show you what the Introduction is?. It shows when the user press the start timer button then the count down timing will be start and the user also press the stop and cancel timer button in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Leave comment

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