Multiple ways to delay code execution in sync and asynchronous way in dart?| Flutter

This tutorial solves the below problems.

  • How to run code after some delay in Flutter?
  • Sleep code for specific time in dart?

Sometimes you want to sleep or delay code execution for a duration of time.

In dart, You can do it in multiple ways. Code execution can be delayed using asynchronous and synchronous way way In asynchronous code execution, you can use use Future. delayed, Stream periodically or Timer class In Synchronous execution, you can use the Sleep method to execute sequentially.

Dart sleep or delay code running with examples

There are multiple ways we can do

  • delay code execution in a synchronous way This program uses the Sleep method.

dart:io package method provides a sleep method, that sleeps thread execution for the duration time object.

void sleep(Duration duration)

A duration is an object created with minutes, hours, seconds, mill, and microseconds.

The below program pauses the current execution for 1 minute and executes the next line in sequence.

import 'dart:io';

void main() {
  print(DateTime.now());
  sleep(new Duration(minutes: 1));
  print(DateTime.now());
}

Output:

2022-04-06 21:37:32.260829
2022-04-06 21:38:32.287419

This approach works sequentially and synchronously as It blocks current thread execution.

  • Asynchronous delay execution We can do it in multiple ways One way using use Future. delayed method dart: async package provides a Future delayed method for asynchronous execution.

It does not block the current thread execution but executes the related code in a separate thread.

import 'dart:async';

void main() {
  print(DateTime.now());
  Future.delayed(const Duration(minutes: 1));
  print(DateTime.now()); .

}

Output:

2022-04-06 21:44:34.659913
2022-04-06 21:44:34.675738

The second way to use the Inbuilt Timer class Timer object created using Duration object that times periods. Here is an example program

import 'dart:async';

void main() {
  print(DateTime.now());
  new Timer(const Duration(seconds: 1), () => print("Executes after 1 second"));
  print(DateTime.now());
}
2022-04-06 21:49:38.827591
2022-04-06 21:49:38.850148
Executes after 1 second

Third way using Stream periodic async Create a stream with periodic and execute the stream 3 times only in asynchronous execution.

import 'dart:async';

void main() {
  print(DateTime.now());
  Stream<int> intStream =
      Stream<int>.periodic(const Duration(seconds: 1), (i) => i + 1);

  intStream = intStream.take(3);
  intStream.listen((event) {
    print("executes  ${event} times");
  });

  print(DateTime.now());
}
2022-04-06 21:57:23.059876
2022-04-06 21:57:23.079258
executes  1 times
executes  2 times
executes  3 times

Conclusion

Based on synchronous and asynchronous delay, you can use one of the approaches.