Dart Future.delayed()
Syntax & Examples

Future.delayed constructor

The `Future.delayed` constructor in Dart creates a future that runs its computation after a specified delay.


Syntax of Future.delayed

The syntax of Future.Future.delayed constructor is:

Future.delayed(Duration duration, [ FutureOr<T> computation() ])

This Future.delayed constructor of Future creates a future that runs its computation after a delay.

Parameters

ParameterOptional/RequiredDescription
durationrequiredThe duration after which the computation should run.
computationoptionalThe computation to be executed. If not provided, defaults to null.


✐ Examples

1 Delayed execution after 2 seconds

In this example,

  1. We use `Future.delayed` with a duration of 2 seconds.
  2. Inside the delayed computation, we print a message.

Dart Program

void main() {
  Future.delayed(Duration(seconds: 2), () {
    print('Delayed execution after 2 seconds.');
  });
}

Output

Delayed execution after 2 seconds.

2 Delayed execution of a string message

In this example,

  1. We create a string variable `message`.
  2. We use `Future.delayed` with a duration of 500 milliseconds.
  3. Inside the delayed computation, we print the message.

Dart Program

void main() {
  String message = 'Hello, Dart!';
  Future.delayed(Duration(milliseconds: 500), () {
    print(message);
  });
}

Output

Hello, Dart!

3 Delayed execution of list items

In this example,

  1. We create a list of strings `fruits`.
  2. We use `Future.delayed` with a duration of 3 seconds.
  3. Inside the delayed computation, we iterate over the list and print each fruit.

Dart Program

void main() {
  List<String> fruits = ['Apple', 'Banana', 'Orange'];
  Future.delayed(Duration(seconds: 3), () {
    for (String fruit in fruits) {
      print(fruit);
    }
  });
}

Output

Apple
Banana
Orange

Summary

In this Dart tutorial, we learned about Future.delayed constructor of Future: the syntax and few working examples with output and detailed explanation for each example.