Giter Club home page Giter Club logo

stop_watch_timer's Introduction

stop_watch_timer

Never inc

Developed with ๐Ÿ’™ by Never inc.


Simple CountUp timer / CountDown timer. It easily create app of stopwatch.

https://pub.dev/packages/stop_watch_timer

./img/countup_timer_demo ./img/countdown_timer_demo

Example code

See the example directory for a complete sample app using stop_watch_timer.

example

Installation

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

dependencies:
  stop_watch_timer:

Features

This is StopWatchMode.

  • CountUp
  • CountDown

CountUp

This is default mode. If you' d like to set it explicitly, set StopWatchMode.countUp to mode.

final stopWatchTimer = StopWatchTimer(
  mode: StopWatchMode.countUp
);

example code

CountDown

Can be set StopWatchMode.countDown mode and preset millisecond.

final stopWatchTimer = StopWatchTimer(
  mode: StopWatchMode.countDown,
  presetMillisecond: StopWatchTimer.getMilliSecFromMinute(1), // millisecond => minute.
);

example code

This is helper functions for presetTime.

/// Get millisecond from hour
final value = StopWatchTimer.getMilliSecFromHour(1); 

/// Get millisecond from minute
final value = StopWatchTimer.getMilliSecFromMinute(60);

/// Get millisecond from second
final value = StopWatchTimer.getMilliSecFromSecond(60 * 60);

Usage

import 'package:stop_watch_timer/stop_watch_timer.dart';  // Import stop_watch_timer

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  final StopWatchTimer _stopWatchTimer = StopWatchTimer(); // Create instance.

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() async {
    super.dispose();
    await _stopWatchTimer.dispose();  // Need to call dispose function.
  }

  @override
  Widget build(BuildContext context) {
    ...
  }
}

To operation stop watch.

// Start timer.
_stopWatchTimer.onStartTimer();


// Stop timer.
_stopWatchTimer.onStopTimer();


// Reset timer
_stopWatchTimer.onResetTimer();


// Lap time
_stopWatchTimer.onAddLap();

Can be set preset time. This case is "00:01.23".

// Set Millisecond.
_stopWatchTimer.setPresetTime(mSec: 1234);

When timer is idle state, can be set this.

// Set Hours. (ex. 1 hours)
_stopWatchTimer.setPresetHoursTime(1);

// Set Minute. (ex. 30 minute)
_stopWatchTimer.setPresetMinuteTime(30);

// Set Second. (ex. 120 second)
_stopWatchTimer.setPresetSecondTime(120);

Using the stream to get the time

_stopWatchTimer.rawTime.listen((value) => print('rawTime $value'));

_stopWatchTimer.minuteTime.listen((value) => print('minuteTime $value'));

_stopWatchTimer.secondTime.listen((value) => print('secondTime $value'));

_stopWatchTimer.records.listen((value) => print('records $value'));

_stopWatchTimer.fetchStopped.listen((value) => print('stopped from stream'));

_stopWatchTimer.fetchEnded.listen((value) => print('ended from stream'));

Display time formatted stop watch. Using function of "rawTime" and "getDisplayTime".

final raw = 3000 // 3sec
final displayTime = StopWatchTimer.getDisplayTime(value); // 00:00:03.00

Using the StreamBuilder to get the time

Example code using stream builder.

StreamBuilder<int>(
  stream: _stopWatchTimer.rawTime,
  initialData: 0,
  builder: (context, snap) {
    final value = snap.data;
    final displayTime = StopWatchTimer.getDisplayTime(value);
    return Column(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.all(8),
          child: Text(
            displayTime,
            style: TextStyle(
              fontSize: 40,
              fontFamily: 'Helvetica',
              fontWeight: FontWeight.bold
            ),
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(8),
          child: Text(
            value.toString(),
            style: TextStyle(
                fontSize: 16,
                fontFamily: 'Helvetica',
                fontWeight: FontWeight.w400
            ),
          ),
        ),
      ],
    );
  },
),
),

Notify from "secondTime" every second.

_stopWatchTimer.secondTime.listen((value) => print('secondTime $value'));

Example code using stream builder.

StreamBuilder<int>(
  stream: _stopWatchTimer.secondTime,
  initialData: 0,
  builder: (context, snap) {
    final value = snap.data;
    print('Listen every second. $value');
    return Column(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.all(8),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              const Padding(
                padding: EdgeInsets.symmetric(horizontal: 4),
                child: Text(
                  'second',
                  style: TextStyle(
                      fontSize: 17,
                      fontFamily: 'Helvetica',
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 4),
                child: Text(
                  value.toString(),
                  style: TextStyle(
                      fontSize: 30,
                      fontFamily: 'Helvetica',
                      fontWeight: FontWeight.bold
                  ),
                ),
              ),
            ],
          )
        ),
      ],
    );
  },
),

Notify from "minuteTime" every minute.

_stopWatchTimer.minuteTime.listen((value) => print('minuteTime $value'));

Example code using stream builder.

StreamBuilder<int>(
  stream: _stopWatchTimer.minuteTime,
  initialData: 0,
  builder: (context, snap) {
    final value = snap.data;
    print('Listen every minute. $value');
    return Column(
      children: <Widget>[
        Padding(
            padding: const EdgeInsets.all(8),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                const Padding(
                  padding: EdgeInsets.symmetric(horizontal: 4),
                  child: Text(
                    'minute',
                    style: TextStyle(
                      fontSize: 17,
                      fontFamily: 'Helvetica',
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 4),
                  child: Text(
                    value.toString(),
                    style: TextStyle(
                        fontSize: 30,
                        fontFamily: 'Helvetica',
                        fontWeight: FontWeight.bold
                    ),
                  ),
                ),
              ],
            )
        ),
      ],
    );
  },
),

Notify lap time.

_stopWatchTimer.records.listen((value) => print('records $value'));

Example code using stream builder.

StreamBuilder<List<StopWatchRecord>>(
  stream: _stopWatchTimer.records,
  initialData: const [],
  builder: (context, snap) {
    final value = snap.data;
    return ListView.builder(
      scrollDirection: Axis.vertical,
      itemBuilder: (BuildContext context, int index) {
        final data = value[index];
        return Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(8),
              child: Text(
                '${index + 1} ${data.displayTime}',
                style: TextStyle(
                  fontSize: 17,
                  fontFamily: 'Helvetica',
                  fontWeight: FontWeight.bold
                ),
              ),
            ),
            const Divider(height: 1,)
          ],
        );
      },
      itemCount: value.length,
    );
  },
),

Using the Callback to get the time

final _stopWatchTimer = StopWatchTimer(
  onChange: (value) {
    final displayTime = StopWatchTimer.getDisplayTime(value);
    print('displayTime $displayTime');
  },
  onChangeRawSecond: (value) => print('onChangeRawSecond $value'),
  onChangeRawMinute: (value) => print('onChangeRawMinute $value'),
);

Parsing Time

Can be used getDisplayTime func. It display time like a real stopwatch timer.

  • Hours
  • Minute
  • Second
  • Millisecond

For example, 1 hours and 30 minute and 50 second and 20 millisecond => "01:30:50.20"

And can be set enable/disable display time and change split character.

stop_watch_timer's People

Contributors

aemelyanovff avatar arturassiscomp avatar ekremkmz avatar goodvibeslab avatar hukusuke1007 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

stop_watch_timer's Issues

Set timer to a specific time without having to reset it.

Hello! Is there a way to set a timer to a specific time without having to reset it as required with the setPresetTime methods? Eg. when I try to do _stopWatchTimer.setPresetMinuteTime(45); I get "Can be not set preset time because of timer is not reset. please reset timer.".

How can you get the value of "DisplayTime" when timer stops ?

Is there a way to get the value of DisplayTime when we stop the timer ?
I use the timer with the StreamBuilder : I use it to time how long it takes the user to do a quiz. When the quiz ends, I execute the STOP method. I would need to get this value stored in a variable : to save it.
Can you help ?

Add support for parsing hours

Hey, I love your plugin!

The only thing stopping me from actually using it is that it does not support hours... which I need for my project :(

I am writing a time tracker destkop app that accumulates the time spent on different tasks on a monthly basis, so as you can imagine, the counter crosses the hour barrier very quickly...

Do you think it's possible to add this functionality in the near future?

Thanks!

[Suggestion] Change the behavior of the static method: getDisplayTime

The parameters RightBreak can only be used as break elements. If the user wants to use them as suffix, it is not necessarily possible. For example, if I want "HH hours" or something like that, it is not possible, it only returns "HH" even if hoursRightBreak is set to " hours". Maybe adding new parameters: hourSuffix, minuteSuffix, secondSuffix, and milliSecondSuffix and making them behave as lasting even if the next time element is not displayed would make it clearer and more flexible. Those who want to use them as right breaks, could do that, and those who want to use them as suffixes could do too.

Dispose method needs to cancel timer

Hi,

Thanks for the great plugin!

Just noticed one small issue in the dispose method. If the timer is started and the widget is then disposed before the timer is stopped, Timer.periodic() will still try to add events to the now closed PublishSubjects. See the error below:

I/flutter (21245): I/flutter (21245): #0 _BroadcastStreamController.add (dart:async/broadcast_stream_controller.dart:249:24) I/flutter (21245): #1 Subject._add package:rxdart/โ€ฆ/subjects/subject.dart:141 I/flutter (21245): #2 Subject.add package:rxdart/โ€ฆ/subjects/subject.dart:135 I/flutter (21245): #3 StopWatchTimer._handle package:stop_watch_timer/stop_watch_timer.dart:185 I/flutter (21245): #4 _rootRunUnary (dart:async/zone.dart:1198:47) I/flutter (21245): #5 _CustomZone.runUnary (dart:async/zone.dart:1100:19) I/flutter (21245): #6 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7) I/flutter (21245): #7 _CustomZone.bindUnaryCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1042:26) I/flutter (21245): #8 _rootRunUnary (dart:async/zone.dart:1206:13) I/flutter (21245): #9 _CustomZone.runUnary (dart:async/zone.dart:1100:19) I/flutter (21245): #10 _CustomZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1026:26) I/flutter (21245): #11 _Closure.call (dart:core-patch/function.dart) I/flutter (21245): #12 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:397:19) I/flutter (21245): #13 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:428:5) I/flutter (21245): #14 _Closure.call (dart:c I/flutter (21245): Error caught by Crashlytics plugin <recordError>: I/flutter (21245): Bad state: Cannot add new events after calling close

I fixed it locally by calling _timer.close(); in the first line of the dispose() method.

setStartTime Function

For me, I wanted to store the Start DateTime and use this to show the stopwatch from this time. So I can exit out of the App, and then return to the same start time, or show the same start time on multiple logins of the app.

Thought this might be useful for others.

//Set the start time to be a particular date and time.
void setStartTime(DateTime startTime) {    
  _startTime = startTime.millisecondsSinceEpoch;    
}

Start timer from preset time

Hi! Is there a way to start the timer from a given time. Instead of starting from 0 minutes 0 hrs, the timer should start from a given hour, minutes, and sec. For example, start from 2 hrs, 36 mins and 46 secs like this.

[feature] Make StopWatchMode not final.

I have this use case:

I create a stopwatch with counting up because time passes by and the user is NOT exercising at the moment.
When the user starts with exercising the stopwatch should count down if it is a timed based set ;-)

Therefore I need a setter for the StopWatchMode or make it not final.
I just need to change very often during user interaction.

Get Raw Second value in a variable

Hi,

Can you please explain, how I can assign the raw second value that is currently printed to an observable variable [I am using Getx for state management]?

The reason that I am asking is that I want to ultimately use this to maintain a database at backend.

Regards,
Ameya

setPresetSecondTime() and setPresetTime() not working as expected when used repeatedly

Good evening,

I'm not sure if I have missunderstood something about how this should work, but when using them several times in a row, they are not acting as you would expect. I'll explain it:

I have implemented a Pause function for the stop watch.

If I call:

void resetToZero(){
  _stopWatchTimer.onStopTimer();
  _stopWatchTimer.onResetTimer();
  _stopWatchTimer.onStartTimer();
}

The timer properly resets to 0 and continues working. I can call it as many times as I want, and it will always work properly.
if I call:

void resetToZeroVersionTwo(){
  _stopWatchTimer.onStopTimer();
  _stopWatchTimer.onResetTimer();
  _stopWatchTimer.setPresetSecondTime(0);
  _stopWatchTimer.onStartTimer();
}

The exact same thing happens. The timer gets reset properly.

However, if I call this:

void resetToTen(){
  _stopWatchTimer.onStopTimer();
  _stopWatchTimer.onResetTimer();
  _stopWatchTimer.setPresetSecondTime(10);
  _stopWatchTimer.onStartTimer();
}

The first time I call it, it works correctly. The timer goes back to 10. But, if I call it more times, it does not work as expected. Instead of reseting to ten every time, the next times, it resets to 10 + the time at which I pressed the reset button. The same happens if I use the "setPresetTime" function instead of the "seconds" version.

Either I'm not understanding something about how these functions should work, or something is bugged. Could someone help me out?

Thank you.

Preset Time

Hello,

Is there a way to force presettime countdown to 0 and set a new preset time ?.

I've tried using clearPresetTime() function, but if i start the stopwatch countdown the stopwatch not start from the new preset time . example : remaining time is 5second and then i call clearPresetTime(), and then i set new preset time 20second and start the countdown again, but the timer started from 15second not 20second
Screenshot_20220519_101150
Screenshot_20220519_101252

Thank you in advance

Cannot stop stopWatch

I use the following commands to start and stop the stopwatch:

_stopWatchTimer.onExecute.add(StopWatchExecute.start);
_stopWatchTimer.onExecute.add(StopWatchExecute.stop);
Unfortunately, the second command does not work, the stopwatch continues to run.

How to preserve state properly?

Hi!

I have been using your package for an app, and so far it works like a charm.
I am unable though to maintain the state of the stopwatch when moving away from the page.

Looking up strategies for maintaining state in Flutter I saw that there are multiple different strategies. I was wondering what the proper way would be to keep the last rawTime in the stopwatch and store it.

Apart from that, I was wondering if it would be feasible to let the timer run in the background after dismissing it?

Thanks in advance!

I get the error 'Can be not set preset time because of timer is not reset. please reset timer.' even though I have reset timer

 void change_timer_value(int song_index) {
    int new_time = get_new_time();
    print(new_time);

    _stopWatchTimer.onExecute.add(StopWatchExecute.reset);
    _stopWatchTimer.setPresetSecondTime(new_time);
  }

I'm trying to change the time of the _stopWatchTimer but when I try to do so it says I have to reset. Then when I try the same thing again it works. Only the first time it says I have to reset. Why does this happen? The problem is that the first reset doesn't update the _stopTime-variable so it can't change the time.

Implement unit tests

The project does not have unit tests yet. Implementing these tests could significantly enhance its reliability and make it more appealing to new users. Also, covering the main functionalities with tests would make it easier to add new functionalities in the future and to fix bugs.

Improve the docstring of some methods and attributes

Some methods and attributes may have their docstring improved. As an example, there is the static method getDisplayTime, which, when the parameter minute receives argument true, has different behavior depending on the argument for the parameter hour.

HELP - How can you trigger an action when countdown reaches 0 ?

I am a beginner developer with Flutter. Am using your package to display a countdown stopwatch. To manage state, I use the package Provider.
Question 1 - Is it possible to manage the stream in my provider file and just "send" the "Displaytime" to the screen where the countdown must be displayed ?
Question 2 - Is there a way to trigger an action when countdown reaches 0 ? In my app, when it reaches 0, it must change part in the test (it's a testing app for English learner). They have 3 minutes to answer 5 questions. (5 questions per part). So when they are out of time, it must change part... I just can't get it to work. I am not very good with Streams, so it's probably where I make a mistake.
Can you help me ?

How Can I make background Timer ?

Hello Sir,
I want to make, Background Timer If i start timer from a page , when i close The page ,it without disposing

value will print in console log
but if i go back to the page Stream Builder start from beginnings,

But console log print old value as well,

Now, how can i get the old value in stream builder?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.