How to: Convert List to List in Dart| Flutter By Example
This tutorial demonstrates how to convert a Future<List>
to List
in Dart and Flutter programming.
Dart and Flutter provide async
and await
keywords for asynchronous operations.
When retrieving data from the backend, it’s loaded asynchronously and displayed on the frontend. Future
is a class for asynchronous operations in Dart applications. It holds values of different types returned from async operations. Its value always returns statuses of uncompleted
and completed
.
Future<List>
signifies that an Async API returns a future list of values.
A list is a collection of elements in Dart programming.
We manually convert from one type to another.
How to Convert Future List to List in Flutter?
The dart:async
package provides classes for async
and await
operations.
Create an async
function and convert a Future
List using Future.value()
. In real-time, this retrieves data from the database. The Async
function always returns Future
Values.
Future.value()
takes an input list of values of dynamic type and returns Future<List>
values.
Syntax:
Future<List<dynamic>> Future.value([FutureOr<List<dynamic>>? value])
Calling the future list using await returns a list.
Here’s the code:
import 'dart:async';
void main() async {
Future<List> listFuture = _getMockData();
List list = await listFuture ;
print(list); // will print [1, 2, 3, 4] on the console.
}
Future<List> _getMockData(){
return Future.value([5,7,33,9]);
}
How to Convert List to Future of List in Flutter?
First, initialize a list with the desired elements.
Create a Future object using the Future.value(
) method by passing the list.
Here’s an example.
import 'dart:async';
void main() async {
List list = [5, 7, 33, 9];
var futureValues = Future.value(list);
print(futureValues); //Instance of '_Future<dynamic>'
print(futureValues.runtimeType); //_Future<dynamic>
}
Conclusion
In conclusion, we can easily convert List to Future<List>
and Future<List>
to List with examples.