Dart Future.sync()
Syntax & Examples

Future.sync constructor

The `Future.sync` constructor in Dart returns a future containing the result of immediately calling computation.


Syntax of Future.sync

The syntax of Future.Future.sync constructor is:

Future.sync(FutureOr<T> computation())

This Future.sync constructor of Future returns a future containing the result of immediately calling computation.

Parameters

ParameterOptional/RequiredDescription
computationrequiredA function returning a value of type `T` or a `FutureOr`, which represents the computation to be performed synchronously.


✐ Examples

1 Immediate computation returning an integer

In this example,

  1. We create an immediate future immediateFuture using the `Future.sync` constructor.
  2. The computation returns an integer value (42) immediately.
  3. We print the result of the synchronous computation using then() method.

Dart Program

void main() {
  Future<int> immediateFuture = Future<int>.sync(() {
    return 42;
  });
  immediateFuture.then((value) {
    print('Result of immediate computation: $value');
  });
}

Output

Result of immediate computation: 42

2 Immediate computation returning a string

In this example,

  1. We create an immediate task immediateTask using the `Future.sync` constructor.
  2. The computation returns a string value ('Hello, World!') immediately.
  3. We print the received message using then() method.

Dart Program

void main() {
  Future<String> immediateTask = Future<String>.sync(() {
    return 'Hello, World!';
  });
  immediateTask.then((value) {
    print('Received message: $value');
  });
}

Output

Received message: Hello, World!

Summary

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