So I was working on a project where I needed to implement a simple stopwatch to let the user know about the time interval spent doing a particular task. Okay, how difficult will that be right? Dart already has a Stopwatch() class that I can use directly.

But as I started working on it, I realized how awfully wrong I was and how such a simple feature is not that easy to implement and how the Stopwatch() class in Dart really sucks! (That is only one person’s opinion. It may not suck for you). And since I am a lazy person, I thought okay lets just search “create a stopwatch in flutter” and then copy the code and paste it. But OH MY GOD! how complex was the code. It was like 1000 lines of code for a simple stopwatch feature. (And its bad practice to use code that you can’t understand).

Image for post

So instead of going through all those 1000 lines of code I decided to write the stopwatch feature myself in as simple way as possible. After 2 hours of coding and a broken glass I was able to manage something like that on the left side.

A Simple Stopwatch with a Start and Reset Button.

And it was accomplished in a fairly low amount of code.( I hope you have the same opinion too after reading the article. Fingers Crossed)

My Thought Process on building The Feature:

Let me take you first through my thought process. I am going to write exactly what was going through my mind (If you want to directly go to the code then you may skip this part).

Okay So I need a timer which looks like 00:00. It should start with a START button and go back to zero with a RESET Button. Ummm… Dart has a stopwatch library right (which I used earlier to calculate time taken by a particular bunch of code). I can use that directly right and display it on the screen. BOOM. I just have to use a Text widget, start the stopwatch (using the Stopwatch() class) and display the elapsed time on Screen.

But wait. I will need to read a different value in the Text Widget every second. So I need to get the data as a Stream. But Unfortunately Stopwatch() class of dart has no method to get the values as a stream. It only outputs a single value whenever one of its methods is called.

So I can’t use it. Okay this is where I realized that this is not going to be as easy as I initially thought.

New Plan. I need to create a Stream which outputs a new value every second. Kind of Like 1,2,3,4,5,6,… Then I can listen to the stream and update the values in the Text Widget. Problem solved (at-least in my mind).

But wait. There is another problem. What happens when the value crossed 60. I can’t show 61,62,63,etc. right. I need to format the values and change it minutes and seconds so that I can display them beautifully.

#flutter #dart #mobile-apps

How to Build a Simple Stopwatch in Flutter
3.75 GEEK