his package provides a Clock class which encapsulates the notion of the "current time" and provides easy access to points relative to the current time.

Related tags

Data clock
Overview

This package provides a Clock class which encapsulates the notion of the "current time" and provides easy access to points relative to the current time. Different Clocks can have a different notion of the current time, and the default top-level clock's notion can be swapped out to reliably test timing-dependent code.

For example, you can use clock in your libraries like this:

// run_with_timing.dart
import 'package:clock/clock.dart';

/// Runs [callback] and prints how long it took.
T runWithTiming<T>(T Function() callback) {
  var stopwatch = clock.stopwatch()..start();
  var result = callback();
  print('It took ${stopwatch.elapsed}!');
  return result;
}

...and then test your code using the fake_async package, which automatically overrides the current clock:

// run_with_timing_test.dart
import 'run_with_timing.dart';

import 'package:fake_async/fake_async.dart';
import 'package:test/test.dart';

void main() {
  test('runWithTiming() prints the elapsed time', () {
    FakeAsync().run((async) {
      expect(() {
        runWithTiming(() {
          async.elapse(Duration(seconds: 10));
        });
      }, prints('It took 0:00:10.000000!'));
    });
  });
}
Comments
  • Pubspec description fix and example

    Pubspec description fix and example

    This fixes a problem that analysis on pub.dev showed with the description in pubspec, and adds a small example of how to use the clock package with fake_async for testing.

    I've been using the clock and fake_async packages a lot and just wrote a blog post about them. While doing that I noticed that they hadn't been updated in a while and their pub.dev score is suffering. I see in the repo that there is a new version ready to post to pub-dev but not yet done. I'm hoping this small PR helps. There are no implementation changes in this PR, just example and docs.

    If you're interested in PRs like this I'll do the same for fake_async.

    opened by sowens-csd 6
  • Clarify copyright holder

    Clarify copyright holder

    I'm trying to figure out who the copyright holder is for this package.

    CONTRIBUTING.md instructs contributors to us a copyright in the source files of: Copyright (c) 2017, the Dart project authors. but the source files actually have copyrights for Google Inc., the pub spec has an author of "Dart Team", and the LICENSE file does not contain a copyright.

    Many open source packages have a copyright statement at the beginning of the LICENSE file which is what I'd suggest if possible.

    Thanks

    opened by kmacdonaO 3
  • Change of Copyright notice

    Change of Copyright notice

    Hello! According to the Appendix of Apache License 2.0, if you want to license your software under this License you should "attach the boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information". This condition is not met now. Please add a copyright notice in the appropriate form, including the year of the software development and your name and surname. Thank you in advance

    Copyright [yyyy] [name of copyright owner]

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

    opened by julia410m 2
  • withClock() behaves inconsistently with test()

    withClock() behaves inconsistently with test()

    Consider this code:

    import 'package:clock/clock.dart';
    import 'package:test/test.dart';
    
    void main() {
      final fakeClock = Clock.fixed(DateTime(2020, 1, 1));
    
      test('inner withClock', () {
        withClock(fakeClock, () {
          expect(clock, same(fakeClock));
        });
      });
    
      withClock(fakeClock, () {
        test('outer withClock', () {
          expect(clock, same(fakeClock));
        });
      });
    }
    

    I don't see anything in the withClock documentation that indicates whether one form is preferred over the other. When I run this with dart this_test.dart, I get:

    00:00 +0: inner withClock
    00:00 +1: outer withClock
    00:00 +1 -1: outer withClock [E]
    
      Expected: same instance as <Instance of 'Clock'>
        Actual: <Instance of 'Clock'>
    

    More weirdness, part 1

    If I reverse the tests, they pass when running it through dart.

    More weirdness, part 2

    The "outer withClock" test by itself fails with flutter test or with pub run test. Each test passes individually when run directly through dart.

    Ultimately I'd like to do:

    withClock(fakeClock, () {
      test(...);
      test(...);
      test(...);
    });
    

    but all of this weirdness seems to prevent that.

    (I'm using Dart 2.8.1 with clock 1.0.1.)

    opened by jamesderlin 2
  • Migrate from Pedantic to Lints

    Migrate from Pedantic to Lints

    Switches linter from the deprecated Pedantic linter to Lints' recommended set. All rules are enabled, bar one - this enabled passing without any need for further code changes (although very open to discussing/fixing/amending)

    opened by Fishbowler 1
  • Bump SDK constraints for pub

    Bump SDK constraints for pub

    Use a 2.12.0 lower bound since pub does not understand allowed experiments for earlier versions.

    Use a 3.0.0 upper bound to avoid a warning in pub and to give some flexibility in publishing for stable.

    opened by natebosch 1
  • Eliminate deprecated CONSTANTS

    Eliminate deprecated CONSTANTS

    This package still uses deprecated Dart 1 SCREAMING CAPS CONSTANTS. These will be removed shortly in Dart 2. This rewriting tool is available for the migration: This tool is available for the migration: https://github.com/dart-lang/dart2_fix .

    opened by leafpetersen 1
  • Remove unnecessary cast from clamp computation.

    Remove unnecessary cast from clamp computation.

    Now that the analyzer correctly computes the type of int.clamp(int, int) as int (for libraries opted into null safety), we no longer need to cast the result to an int.

    opened by stereotype441 0
  • Flutter's WidgetsFlutterBinding.ensureInitialized() and withClock() - causes clock.now() to misbehave

    Flutter's WidgetsFlutterBinding.ensureInitialized() and withClock() - causes clock.now() to misbehave

    If flutter app starts with:

    void main() {
      WidgetsFlutterBinding.ensureInitialized();
    

    Then clock.now() prints not mocked value if outside of build method.

    Minimum reproduceable code:

    import 'package:clock/clock.dart';
    import 'package:flutter/material.dart';
    
    void main() {
      WidgetsFlutterBinding.ensureInitialized();
      
      withClock(Clock.fixed(DateTime(1990)), () {
        runApp(const MyApp());
      });
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);
    
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: const MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      const MyHomePage({Key? key, required this.title}) : super(key: key);
    
      final String title;
    
      @override
      State<MyHomePage> createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      void _printClockNow() {
        print('_printClockNow is: ${clock.now()}'); // prints real NOW
        setState(() {});
      }
    
      @override
      Widget build(BuildContext context) {
        print('build clock.now() is: ${clock.now()}'); // prints mocked NOW
    
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[Dummy()],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _printClockNow,
            tooltip: 'Increment',
            child: const Icon(Icons.add),
          ),
        );
      }
    }
    
    class Dummy extends StatelessWidget {
      @override
      Widget build(Object context) {
        return Text('t: ${clock.now()}');
      }
    }
    

    Expected behavior: clock.now() to have mocked value despite WidgetsFlutterBinding.ensureInitialized()

    EDIT: Changed because I discovered that culprit is WidgetsFlutterBinding.ensureInitialized().

    opened by mpszczolinski 2
Owner
Dart
Dart is an open-source, scalable programming language, with robust libraries and runtimes, for building web, server, and mobile apps.
Dart
Moor is an easy to use, reactive, typesafe persistence library for Dart & Flutter

Moor is an easy to use, reactive, typesafe persistence library for Dart & Flutter

Simon Binder 1.8k Dec 30, 2022
Dart package for accessing databases.

Introduction This is database.dart, a vendor-agnostic database access API for Flutter and other Dart projects. This version is just an early preview.

Dint 63 Jan 2, 2023
Create a DataTable with Flutter to display data in columns, rows, and cells and also learn how to sort the data within the table.

Flutter Tutorial - Sortable DataTable Create a DataTable with Flutter to display data in columns, rows, and cells and also learn how to sort the data

Johannes Milke 22 Oct 9, 2022
:fire:GeoFlutterFire:fire: is an open-source library that allows you to store and query firestore documents based on their geographic location.

GeoFlutterFire ?? GeoFlutterFire is an open-source library that allows you to store and query a set of keys based on their geographic location. At its

Darshan N 282 Dec 11, 2022
Shared SQLite DB across mobile, web and desktop

moor_shared An example project to demonstrate how moor can be used on multiple platforms (Web, android, iOS, macOS, Windows and Linux). Note: You need

Rody Davis 143 Nov 28, 2022
Hive is a lightweight and blazing fast key-value database

Hive Manager Hive is a lightweight and blazing fast key-value database Features Cross platform -> mobile, desktop Performance Strong encryption built

Okan 2 Feb 24, 2022
AsyncCallQueue is a Dart class which provides a queuing mechanism to prevent concurrent access to asynchronous code.

async_call_queue AsyncCallQueue is a Dart class which provides a queuing mechanism to prevent concurrent access to asynchronous code. Getting Started

Ron Booth 2 Jan 18, 2022
Dart library for parsing relative date and time.

Dateparser Dart library for parsing relative date and time. Examples just now a moment ago tomorrow today yesterday 10 days remaining 2 hours ago 2 mo

Mensch272 5 Sep 20, 2022
Gradi clock - Gradi Clock face for Flutter Clock challenge

Gradi Clock Clock face made for Flutter Clock challenge. About There is an abundant body of research that suggests that people are sensory creatures w

Janko Djuric 4 Sep 29, 2021
Magpie-fly is a component library produced by 58 Group, which encapsulates a variety of common components to meet the needs of developers

[toc] magpie_fly Magpie-fly 是58集体出品组件库,封装了多种常用组件,以满足开发者需求。(Magpie-fly is a component library produced by 58 Group, which encapsulates a variety of com

Wuba 40 Mar 18, 2022
Flutter plugin to display a simple flat world map with animated points in real time

Flutter Simple Map Flutter plugin to display a simple flat world map with animated points in real time. Can be used as a presentation of online users,

Vladyslav Korniienko 7 Dec 8, 2022
A clock created for the Flutter Clock challenge which achieved an honourable mention.

Circle Clock A clock created for the Flutter Clock challenge. Shaded circles representing hour, minute and second hands move across the screen, while

Max 11 Apr 18, 2022
A new Flutter project. Use of Padding Class(Widget) and Card Class (Widget)

Use_Of_Card_And_Padding_Class A new Flutter project. Use of Padding Class(Widget) and Card Class (Widget) Getting Started This project is a starting p

Avinandan Bose 1 Mar 18, 2022
Calculates the convex hull of a given set of points.

Calculates the convex hull of a given set of points. Monotone chain is used as algorithm. Info Given a set of points, the convex hull is a subset of p

Daniel 2 Sep 7, 2022
Flutter plugin that leverages Storage Access Framework (SAF) API to get access and perform the operations on files and folders.

Flutter plugin that leverages Storage Access Framework (SAF) API to get access and perform the operations on files and folders.

Vehement 8 Nov 26, 2022
An application for the time recording of his working hours.

Time24 An open-source time-tracking software About the project! The purpose of this project is to simplify the documentation of working hours and at t

null 5 Aug 3, 2021
This flutter package provides an easy implementation of a Slider Button to cancel current transaction or screen

This flutter package provides an easy implementation of a Slider Button to cancel current transaction or screen

null 222 Nov 8, 2022
This is a simple mobile application which calculates the person expenses during each week and tracks up where he spend his money!

Presonal Expenses Tracker Table of content About the project built with Getting Started installation Running ScreenShots About This is a simple mobile

Abdelaziz Salah 8 Nov 3, 2022
Simple URL-shorter written in Dart with Notion as a database

Tuda A simple URL-shorter service written in pure Dart. With Notion as a database, it provides the simplest interface for setting your links. Environm

Parabola 8 Aug 19, 2022
Notion API client for dart

Notion API client for dart. See the ROADMAP file to see what is coming next. API implemented Usage NotionClient class Individual classes A few example

Jonathan Gómez 22 Oct 9, 2022