Dart Future.microtask()
Syntax & Examples
Future.microtask constructor
The `Future.microtask` constructor in Dart creates a future containing the result of calling a computation asynchronously with `scheduleMicrotask`.
Syntax of Future.microtask
The syntax of Future.Future.microtask constructor is:
Future.microtask(FutureOr<T> computation())
This Future.microtask constructor of Future creates a future containing the result of calling computation asynchronously with scheduleMicrotask.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
computation | required | The computation to be executed asynchronously. |
✐ Examples
1 Execution of a microtask
In this example,
- We use `Future.microtask` to execute a microtask asynchronously.
- Inside the microtask, we print a message.
Dart Program
void main() {
Future.microtask(() {
print('Microtask executed.');
});
}
Output
Microtask executed.
2 Execution of a computation with a variable
In this example,
- We create an integer variable `num` with the value 10.
- We use `Future.microtask` to execute a microtask asynchronously.
- Inside the microtask, we print the double of `num`.
Dart Program
void main() {
int num = 10;
Future.microtask(() {
print('Double of $num is ${num * 2}');
});
}
Output
Double of 10 is 20
3 Execution of a microtask with a list
In this example,
- We create a list of integers `numbers`.
- We use `Future.microtask` to execute a microtask asynchronously.
- Inside the microtask, we iterate over the list and print each number.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
Future.microtask(() {
for (int number in numbers) {
print(number);
}
});
}
Output
1 2 3 4 5
Summary
In this Dart tutorial, we learned about Future.microtask constructor of Future: the syntax and few working examples with output and detailed explanation for each example.