How to Create a Timer Widget in Flutter?

In this tutorial, we’ll create a simple yet effective timer widget in Flutter. In mobile app development, timers are often utilized for various purposes, such as countdowns, tracking elapsed time, or implementing features like OTP verification.

As a versatile framework, Flutter offers convenient tools for efficiently implementing timers.

How to create a timer widget in Flutter

timer widget in Flutter – let’s understand the code

Let’s break down the code provided:

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

class OtpTimer extends StatefulWidget {
  @override
  _OtpTimerState createState() => _OtpTimerState();
}

class _OtpTimerState extends State<OtpTimer> {
  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 – The timer widget in Flutter

  • OtpTimer is a StatefulWidget which allows it to dynamically update its state.
  • _OtpTimerState is the state class associated with OtpTimer.
  • interval defines the duration of each tick of the timer, set to one second.
  • timerMaxSeconds sets the maximum duration of the timer, in this case, 60 seconds.
  • currentSeconds keeps track of the current elapsed time.
  • timerText generates the text to display in the widget, showing the remaining time in MM : SS format.
  • startTimeout() initializes and starts the timer using Timer.periodic().
  • initState() is called when the stateful widget is initialized, starting the timer.

Let’s break down the timerText getter method step by step:

  1. timerMaxSeconds - currentSeconds: This calculates the remaining time in seconds by subtracting the currentSeconds (elapsed time) from the timerMaxSeconds (maximum duration of the timer).
  2. ((timerMaxSeconds - currentSeconds) ~/ 60): This part calculates the minutes remaining in the timer. The ~/ operator is the integer division operator, which divides the result (timerMaxSeconds - currentSeconds) by 60 and returns the integer part of the result.
  3. .toString().padLeft(2, '0'): This converts the minutes to a string and pads it with zeros on the left side if it’s less than two digits. This ensures that minutes are displayed with two digits, maintaining a consistent format.
  4. ((timerMaxSeconds - currentSeconds) % 60): This calculates the remaining seconds after subtracting the minutes calculated in the previous step. The % operator is the modulo operator, which returns the remainder of dividing (timerMaxSeconds - currentSeconds) by 60, giving us the remaining seconds.
  5. .toString().padLeft(2, '0'): Similar to step 3, this converts the seconds to a string and pads it with zeros on the left side if it’s less than two digits.
  6. The entire expression is then formatted as 'MM : SS Sec', where MM represents minutes and SS represents seconds.

How to Use the timer widget in Flutter

To use the OtpTimer widget in your Flutter application:

  1. Import the file where the OtpTimer class is defined.
  2. Place the OtpTimer widget within your UI code, wherever you want to display the timer.

For eg:

import 'package:flutter/material.dart';

// Import the OtpTimer widget from the file

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Timer Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Timer Demo'),
      ),
      body: Center(
        child: OtpTimer(), // Place the OtpTimer widget here
      ),
    );
  }
}

Output:

output of timer widget in Flutter

Also Read:

Conclusion

Creating a timer widget in Flutter is straightforward, thanks to its rich set of libraries and tools. With the provided code, you can easily integrate a timer into your Flutter applications, enhancing their functionality and user experience.

Feel free to customize the timer widget further to suit your specific requirements and design preferences.

You can visit Flutter’s official documentation for more.

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