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
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. |
✐ Examples
1 Delayed execution after 2 seconds
In this example,
- We use `Future.delayed` with a duration of 2 seconds.
- 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,
- We create a string variable `message`.
- We use `Future.delayed` with a duration of 500 milliseconds.
- 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,
- We create a list of strings `fruits`.
- We use `Future.delayed` with a duration of 3 seconds.
- 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.