A customizable timer builder, with controller, animation, intervals, callbacks and custom actions for Flutter.

Overview

Custom Timer

A highly customizable timer builder, with controller, animation, intervals, callbacks, custom actions, and more!


Example image


📌 Simple Usage

@override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text("CustomTimer example"),
        ),
        body: Center(
          child: CustomTimer(
            from: Duration(hours: 12),
            to: Duration(hours: 0),
            onBuildAction: CustomTimerAction.auto_start,
            builder: (CustomTimerRemainingTime remaining) {
              return Text(
                "${remaining.hours}:${remaining.minutes}:${remaining.seconds}",
                style: TextStyle(fontSize: 30.0),
              );
            },
          ),
        ),
      ),
    );
  }

📌 Custom Usage

Options that allow for more control:

Properties Type Description
from Duration The start of the timer.
to Duration The end of the timer.
interval Duration The time interval to update the widget.
The default interval is Duration(seconds: 1).
controller CustomTimerController Controls the state of the timer.
onBuildAction CustomTimerAction Execute an action when the widget is built for the first time.
The default action is CustomTimerAction.go_to_start.
onFinishAction CustomTimerAction Execute an action when the timer finish.
The default action is CustomTimerAction.go_to_end.
onResetAction CustomTimerAction Executes an action when the timer is reset.
The default action is CustomTimerAction.go_to_start.
builder Widget Function(CustomTimerRemainingTime) Function that builds a custom widget and allows to obtain the remaining time of the timer.
finishedBuilder Widget Function(CustomTimerRemainingTime) Function that builds a custom widget and allows to get the remaining time only when the timer has finished.
If you use it, it will replace builder.
pausedBuilder Widget Function(CustomTimerRemainingTime) Function that builds a custom widget and allows to get the remaining time only when the timer is paused.
If you use it, it will replace builder.
resetBuilder Widget Function(CustomTimerRemainingTime) Function that builds a custom widget and allows to get the remaining time only when the timer is reset.
If you use it, it will replace builder.
onStart VoidCallback Callback function that runs when the timer start.
onFinish VoidCallback Callback function that runs when the timer finish.
onPaused VoidCallback Callback function that runs when the timer is paused.
onReset VoidCallback Callback function that runs when the timer is reset.
onChangeState Function(CustomTimerState) Callback function that runs when the timer state changes. Returns a CustomTimerState that allows you to get the state and create custom functions or conditions.
onChangeStateAnimation AnimatedSwitcher Animation that runs when the state of the timer changes. It is not necessary to define a child because it will be replaced by the current builder.

CustomTimerAction actions:

Actions Description
CustomTimerAction.go_to_start Shows the start of the timer.
CustomTimerAction.go_to_end Shows the end of the timer.
CustomTimerAction.auto_start Automatically starts the timer.

CustomTimerRemainingTime properties:

Properties Description
days A string with the remaining days.
hours A string with the remaining hours.
hoursWithoutFill A String with the remaining hours and only with two digits when necessary.
minutes A string with the minutes remaining.
minutesWithoutFill A String with the remaining minutes and only with two digits when necessary.
seconds A string with the seconds remaining.
secondsWithoutFill A String with the remaining seconds and only with two digits when necessary.
milliseconds A string with the remaining milliseconds.
duration A default Duration with remaining time.
Lets you create more specific functions or conditions, but remember that it can return more than 59 minutes and seconds and more than 1000 milliseconds.

CustomTimerState states:

States
CustomTimerState.reset
CustomTimerState.counting
CustomTimerState.paused
CustomTimerState.finished

You can access the timer state from the onChangeState callback function or using a CustomTimerController.
For example:

CustomTimerState state = _controller.state;

📌 Using the CustomTimerController

[ CustomTimer( controller: _controller, from: Duration(hours: 12), to: Duration(hours: 0), builder: (CustomTimerRemainingTime remaining) { return Text( "${remaining.hours}:${remaining.minutes}:${remaining.seconds}", style: TextStyle(fontSize: 30.0), ); }, ), SizedBox(height: 16.0,), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ FlatButton( child: Text("Start"), onPressed: () => _controller.start(), color: Colors.green, ), FlatButton( child: Text("Pause"), onPressed: () => _controller.pause(), color: Colors.blue, ), FlatButton( child: Text("Reset"), onPressed: () => _controller.reset(), color: Colors.red ), ], ) ], ), ), ); } ">
  final CustomTimerController _controller = new CustomTimerController();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text("CustomTimer example"),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            CustomTimer(
              controller: _controller,
              from: Duration(hours: 12),
              to: Duration(hours: 0),
              builder: (CustomTimerRemainingTime remaining) {
                return Text(
                  "${remaining.hours}:${remaining.minutes}:${remaining.seconds}",
                  style: TextStyle(fontSize: 30.0),
                );
              },
            ),
            SizedBox(height: 16.0,),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                FlatButton(
                  child: Text("Start"),
                  onPressed: () => _controller.start(),
                  color: Colors.green,
                ),
                FlatButton(
                  child: Text("Pause"),
                  onPressed: () => _controller.pause(),
                  color: Colors.blue,
                ),
                FlatButton(
                  child: Text("Reset"),
                  onPressed: () => _controller.reset(),
                  color: Colors.red
                ),
              ],
            )
          ],
        ),
      ),
    );
  }

CustomTimerController properties:

Properties Permissions Description
state Read Returns the current state of the timer.

CustomTimerController methods:

Methods Description
start() Start or resume the timer.
pause() Pause the timer.
reset() Reset the timer.
If you want to restart the timer, you can call the controller start() method or set the onResetAction property to CustomTimerAction.auto_start.

⚙️ Installation

Add this to your package's pubspec.yaml file:

dependencies:
  custom_timer: ^0.0.6

Install it:

$ flutter pub get

Import the package in your project:

import 'package:custom_timer/custom_timer.dart';
Comments
  • fix disposing of controller

    fix disposing of controller

    This is my first pull request and contribution to a public repository. I'm also pretty new on Flutter. I added a bool variable in order to avoid the disposing of the controller when it's passed by parameter. Fixing in this way the issue #14

    opened by gigi214 7
  • 'finishedBuilder', 'resetBuilder' don't fire

    'finishedBuilder', 'resetBuilder' don't fire

    Hi, thank you for the awesome Timer, it's really customizable, but I have one issue. According to the code, these builders will fire only when controller is provided. Why? image image

    opened by Apollo108 6
  • Controller is dispose after state is finished

    Controller is dispose after state is finished

    I am trying to set up a countdown timer but it keeps throwing an error. Controller is already disposed here's my code

    CustomTimer(
        controller: controller,
        begin: Duration(seconds: 30),
        end: Duration(seconds: 0),
        onChangeState: (s) {
          if(s == CustomTimerState.finished) {
            print("We completed finished");
            // Prevent calling setState during a widget build
            showTimer.value = false;
            controller.reset();
          }
        },
        builder: (remaining) {
          return Text("${remaining.minutes}:${remaining.seconds}", style: TextStyle(
            fontFamily: "Montserrat",
            fontWeight: FontWeight.w600,
            color: primaryColor,
            fontSize: 14,
          ));
        },
      ),
    
    opened by BrianMwas 4
  • The timer goes bellow 0

    The timer goes bellow 0

    I was expecting the behaviour of onFinish to be triggered when it gets to Duration(seconds: 0) yet it didn't and it continued to negative values, is this a bug? thanks!

     Widget _timer() {
        return CustomTimer(
          controller: _timerController,
          from: widget.durationLeft,
          to: Duration(seconds: 0),
          interval: Duration(seconds: 1),
          onFinish: () => widget.onFinish(),
          onBuildAction: CustomTimerAction.auto_start,
          builder: (CustomTimerRemainingTime remaining) {
            return Text('${remaining.hours}:${remaining.minutes}:${remaining.seconds}');
          },
        );
      }
    
    opened by cesarferreira 4
  • When I use microseconds, onFinished isn't triggered

    When I use microseconds, onFinished isn't triggered

    I need a custom duration: eventDate.difference(DateTime.now()) for the from Yet the onFinished wasn't being triggered so I tried to add microseconds to the from property and indeed it doesn't trigger it and continue to countdown below 0

    	from: Duration(seconds: 10, microseconds: 11111),
    
    CustomTimer(
      from: Duration(seconds: 10, microseconds: 11111),
      to: Duration(hours: 0),
      onBuildAction: CustomTimerAction.auto_start,
      onFinish: () => _refreshData(),
      builder: (CustomTimerRemainingTime remaining) {
        return Text(
          '${remaining.hours}:${remaining.minutes}:${remaining.seconds}')
        );
      },
    )
    

    A workaround that works is convert to seconds and convert to Duration

    from: Duration(seconds: Duration(seconds: 10, microseconds: 11111).inSeconds),
    
    opened by cesarferreira 2
  • Counter is going down instead of up

    Counter is going down instead of up

    on version 0.0.3 this worked fine but since I upgraded to 0.0.5 the counter goes down to negative values

    CustomTimer(
          controller: _controller,
          from: Duration(seconds: 0),
          to: Duration(hours: 10),
          interval: Duration(milliseconds: 500),
          onBuildAction: CustomTimerAction.auto_start,
          builder: (CustomTimerRemainingTime remaining) {
            return Text(
              '${remaining.minutes}:${remaining.seconds}',
              style: _tema.title2().copyWith(color: _tema.backgroundTertiary()),
            );
          },
        )
    
    opened by cesarferreira 2
  • Timer doesn't auto start

    Timer doesn't auto start

    Hi, previously I used "onBuildAction: CustomTimerAction.auto_start", but now it's gone, and the timer doesn't auto start. How to auto start on build without using the external controller?

    opened by Apollo108 1
  • milliseconds not working

    milliseconds not working

    CustomTimer( from: Duration(milliseconds: 0), to: Duration(hours: 1), onBuildAction: CustomTimerAction.auto_start, builder: (CustomTimerRemainingTime remaining) { return Text( "${remaining.minutes}:${remaining.seconds}:${remaining.milliseconds} ", style: TextStyle(fontSize: 20.0), ); }, ),

    https://user-images.githubusercontent.com/34600049/128942222-1531381f-2b6e-491e-b1e6-0e3bb7c07b93.mov

    opened by DjamikTea 1
  • Timer between multiple screens

    Timer between multiple screens

    I want to use the same time accessed between multiple screens, The timer is resetting in every screen currently, even when I use the same controller.

    And when I come back to the previous screen, two instances of the timer running.

    I want one instance of the timer used across multiple screens, do we have an option for that?

    opened by vijayb95 1
  • Issue: Classic flutter issue of insane & needless rebuilds eating resources - Propose: Less rebuilds for situations where NOT using milliseconds value of CustomTimerRemainingTime

    Issue: Classic flutter issue of insane & needless rebuilds eating resources - Propose: Less rebuilds for situations where NOT using milliseconds value of CustomTimerRemainingTime

    Love this package, nice and simple & thank you for producing it. Now, I think something important could be improved.

    I'm no Flutter pro engineer, mega computer genius, crazy Stephen Hawking intellectual, but rebuilding a widget a million times per second has always since I started learning Flutter been a serious main issue, concern & my arch nemesis and looks like Flutter's also. However it is also necessary IF one is showing milliseconds as part of their timer. I can understand this aspect of the programming. This uses enormous system resources in debug mode.

    So my proposal is to include some sort of boolean value updateForMilliseconds or something which uses state and does not rebuild so much when not necessary when not using milliseconds value from timer. If using milliseconds then use the good old stateful widget and rebuild it quickly so user can see milliseconds passing.

    I suppose all timers would have this issue and this is why I think this could be very valuable when some don't need rapid updates.

    Showing my performance issue

    class OTPTimer extends StatelessWidget {
      final CustomTimerController timeController;
    
      const OTPTimer({
        required this.timeController,
        Key? key,
      }) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return CustomTimer(
            controller: timeController,
            begin: const Duration(minutes: 10),
            end: const Duration(minutes: 0),
            builder: (timeRemaining) {
              return Text(
                "${timeRemaining.hours}:${timeRemaining.minutes}:${timeRemaining.seconds}",
                style: timerStyle(timeRemaining),
              );
            });
      }
    
      // // Timer time text
      TextStyle timerStyle(CustomTimerRemainingTime timeRemaining) {
        print(int.parse(timeRemaining.secondsWithoutFill));                          // Prints 40-60 times per second (useless in my case)
        // Green indicator text
        if (int.parse(timeRemaining.minutesWithoutFill) > 3) {
          return ThemeEndpoints.infoHeaderPositive();
        }
        // Yellow indicator warning text
        if (int.parse(timeRemaining.minutesWithoutFill) < 3 &&
            int.parse(timeRemaining.minutesWithoutFill) > 1) {
          return ThemeEndpoints.infoHeaderWarning();
        }
        // Red indicator warning text
        return ThemeEndpoints.infoHeaderNegative();
      }
    
    opened by SexyBeast007 0
  • Feature:  Would be nice to have onCompleted to take action when the counter reaches the end

    Feature: Would be nice to have onCompleted to take action when the counter reaches the end

    When the counter reaches the end its still in CustomTimerState.counting. I would like to take action and update certain state values once the clock hits 00:00:00. What would be the best way to do that please?

    opened by Sureya 0
  • Request: Being able to access current state of timer

    Request: Being able to access current state of timer

    It would be nice to be have the controller be able to keep track of the timer regardless of whether or not the timer is in view or not.

    I envision the controller being the source of truth for the timer widget and the widget simply latches on to the current state of the controller it was initialized with whenever it comes into view. This way we can get and set the timer from just the controller in other parts of an app.

    The initial discussions for this issue can be found here.

    enhancement 
    opened by leo-paz 2
The most complete Chat UI for flutter highly customizable and helps developing chat UI faster.

⚠️ Dashchat v2 is available in v2 branch ⚠️ You can open issues for the v2 to indicate things we need to implement/fix. Also the API can change until

Fayeed Pawaskar 432 Dec 11, 2022
A customizable shadow for any widget

simple_shadow A customizable shadow for any widget Getting Started import: import 'package:simple_shadow/simple_shadow.dart'; example: SimpleShadow(

Marcelo Pinheiro Montanher 27 Nov 23, 2022
A customizable segment tab control. Can be used with or without TabView.

A customizable segment tab control. Can be used with or without TabView. Features The package provides an advanced segmented control widget based on t

null 11 Nov 16, 2022
A Splash screen with curved custom bottom sheet and dots indicator within it.

Pub.dev Curved Splash Screen A Splash screen with curved custom bottom sheet and dots indicator within it. You can add your custom splash screens acco

Hosain Mohamed 16 Dec 1, 2022
Flutter Beautiful Login Page design and Animation - day 12

Flutter Beautiful Login Page design and Animation - day 12

Mohammad Rahmani 296 Jan 1, 2023
A flutter package that contains a collection of icon decoration tools (i.e. gradient, opacity) and icon transition features with cool animation effects.

Advanced Icon A flutter package that contains a collection of icon decoration tools (i.e. gradient, opacity) and icon transition features with cool an

Ankit Mishra 8 Dec 24, 2021
Custom widget for Flutter

Flushbar Use this package if you need more customization when notifying your user. For Android developers, it is made to substitute toasts and snackba

Andre Haueisen 899 Dec 30, 2022
🔁 A custom refresh indicator for flutter.

Liquid Pull To Refresh A beautiful and custom refresh indicator for flutter highly inspired from Ramotion Pull Down to Refresh. Table of contents Inst

Ayush Agarwal 1.1k Jan 8, 2023
A custom is strong dropdown menu for Flutter

A custom is strong dropdown menu for Flutter. Easy to use and powerful for customization, it's up to you what you want to display in the dropdown menu!

干志雄 662 Dec 26, 2022
A simple widget for animating a set of images with full custom controls as an alternative to using a GIF file.

image_sequence_animator A simple widget for animating a set of images with full custom controls as an alternative to using a GIF file. If you have a G

AliYigitBireroglu 134 Dec 22, 2022
this repo is testing the custom painter by changing according to slider value. It was intended to be used for volume control in audio player.

custom_paint_demo Trying a widget called custom paint Getting Started This project is a starting point for a Flutter application. A few resources to g

Edy 7 Jan 16, 2022
The app to demo animation with Flutter by implement Facebook reactions

Facebook Reactions Animation Description The app to demo animation with Flutter by implement Facebook reactions. Watch the demo video for more clarity

Duy Tran 318 Jan 8, 2023
Flutter Animation - Grocery App UI

Flutter Animation - Grocery App UI Packages we are using: flutter_svg: link goole_fonts: link Fonts Poppins link creating a custom animation Grocery A

null 1 Feb 14, 2022
A package for flip panel with built-in animation

Flip Panel A package for flip panel with built-in animation How to use import 'package:flip_panel/flip_panel.dart'; Create a flip panel from iterable

HungHD 554 Dec 30, 2022
Foody - Flutter project to display foods to clients and display charts and has a lot of features , two flutter apps : Android and Web

Foody Flutter project to display foods to the clients and use charts and use a lot of features to complete the process (HUGE APP) There two apps: Andr

ABDULKARIMALBAIK 1 Feb 7, 2022
A flutter package to display a country, states, and cities. In addition it gives the possibility to select a list of countries, States and Cities depends on Selected, also you can search country, state, and city all around the world.

A flutter package to display a country, states, and cities. In addition it gives the possibility to select a list of countries, States and Cities depends on Selected, also you can search country, state, and city all around the world.

Altaf Razzaque 25 Dec 20, 2022
Instagram UI designed with Flutter; it is compatible and responsive with any type of Android and iOS devices.

instagram Instagram clone UI designed with Flutter; it is compatible and responsive with any type of Android and iOS devices . Getting Started This pr

Mustafa Nabavi 4 Oct 28, 2021
A set of interesting and fun UI components, animations and routes for Flutter.

すごい ・ Sugoi A set of interesting and fun UI components, animations and routes for Flutter. By Jay (Jeroen) Meijer. This project was bootstrapped by Ve

Jeroen Meijer (Jay) 5 Jan 22, 2022
Tour guide App UI in Flutter Consist of Three Pages. First Screen is Splash Screen , Second is welcome screen routing to third Screen and Third screen consist of details , navigation, places, and responsive UI.

Tour Guide // Tourism App Ui in Flutter. Tour Guid App Ui in Flutter. Visit Website Features State Management Navigation Bar Responsive Design Hybrid

Habib ullah 2 Nov 14, 2022