The `Future.sync` constructor in Dart returns a future containing the result of immediately calling computation.
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.
Parameter | Optional/Required | Description |
---|---|---|
computation | required | A function returning a value of type `T` or a `FutureOr |
In this example,
immediateFuture
using the `Future.sync` constructor.then()
method.void main() {
Future<int> immediateFuture = Future<int>.sync(() {
return 42;
});
immediateFuture.then((value) {
print('Result of immediate computation: $value');
});
}
Result of immediate computation: 42
In this example,
immediateTask
using the `Future.sync` constructor.then()
method.void main() {
Future<String> immediateTask = Future<String>.sync(() {
return 'Hello, World!';
});
immediateTask.then((value) {
print('Received message: $value');
});
}
Received message: Hello, World!
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.