Tickers in Dart

Our first example demonstrates the use of tickers in Dart. Tickers are used when you want to perform an action repeatedly at regular intervals. Here’s an example of a ticker that ticks periodically until we stop it.

import 'dart:async';

void main() {
  // Create a ticker that ticks every 500 milliseconds
  var ticker = Stream.periodic(Duration(milliseconds: 500));
  var subscription;

  // Use a flag to control when to stop the ticker
  var done = false;

  subscription = ticker.listen((event) {
    if (done) {
      subscription.cancel();
      print('Ticker stopped');
      return;
    }
    print('Tick at ${DateTime.now()}');
  });

  // Stop the ticker after 1600 milliseconds
  Future.delayed(Duration(milliseconds: 1600), () {
    done = true;
  });
}

In this example, we use Dart’s Stream.periodic to create a ticker that emits events every 500 milliseconds. We then listen to this stream and print the current time for each tick.

The ticker will continue to tick until we set the done flag to true, which happens after a delay of 1600 milliseconds. Once done is set to true, we cancel the subscription and print a message indicating that the ticker has stopped.

When we run this program, the ticker should tick 3 times before we stop it:

$ dart run tickers.dart
Tick at 2023-06-05 15:30:00.500
Tick at 2023-06-05 15:30:01.000
Tick at 2023-06-05 15:30:01.500
Ticker stopped

This example demonstrates how to create and manage tickers in Dart, which can be useful for tasks that need to be performed at regular intervals.