Dart Future.value()
Syntax & Examples
Future.value constructor
The `Future.value` constructor in Dart creates a future that is completed with a specified value.
Syntax of Future.value
The syntax of Future.Future.value constructor is:
Future.value([FutureOr<T> value ])
This Future.value constructor of Future creates a future completed with value.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
value | optional | The value with which the future should be completed. Defaults to null if not provided. |
✐ Examples
1 Completion of a future with an integer value
In this example,
- We create a future using `Future.value` with an integer value of 42.
- We use `then` to handle the completion of the future and print the completed value.
Dart Program
void main() {
Future<int> future = Future.value(42);
future.then((value) {
print('Future completed with value: $value');
});
}
Output
Future completed with value: 42
2 Completion of a future with a string value
In this example,
- We create a string variable `message`.
- We create a future using `Future.value` with the string message.
- We use `then` to handle the completion of the future and print the completed value.
Dart Program
void main() {
String message = 'Hello, Dart!';
Future<String> future = Future.value(message);
future.then((value) {
print(value);
});
}
Output
Hello, Dart!
3 Completion of a future with a list
In this example,
- We create a list of integers `numbers`.
- We create a future using `Future.value` with the list.
- We use `then` to handle the completion of the future and print the completed list.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
Future<List<int>> future = Future.value(numbers);
future.then((value) {
print(value);
});
}
Output
[1, 2, 3, 4, 5]
Summary
In this Dart tutorial, we learned about Future.value constructor of Future: the syntax and few working examples with output and detailed explanation for each example.