The `Future.delayed` constructor in Dart creates a future that runs its computation after a specified delay.
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.
Parameter | Optional/Required | Description |
---|---|---|
duration | required | The duration after which the computation should run. |
computation | optional | The computation to be executed. If not provided, defaults to null. |
In this example,
void main() {
Future.delayed(Duration(seconds: 2), () {
print('Delayed execution after 2 seconds.');
});
}
Delayed execution after 2 seconds.
In this example,
void main() {
String message = 'Hello, Dart!';
Future.delayed(Duration(milliseconds: 500), () {
print(message);
});
}
Hello, Dart!
In this example,
void main() {
List<String> fruits = ['Apple', 'Banana', 'Orange'];
Future.delayed(Duration(seconds: 3), () {
for (String fruit in fruits) {
print(fruit);
}
});
}
Apple Banana Orange
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.