How to: Convert List to List in Dart| Flutter By Example
This tutorial shows you how to Convert Future<List>
to List
in Dart and Flutter programming.
Dart and flutter provide async and await keywords for asynchronous.
When you are retrieving the data from the backend, loaded it asynchronously and display it in the frontend.
Future
are classes for asynchronous operations in the Dart application.
It holds the values of different types returned from async operations. Its value always returns status uncompleted and completed.
Future<List>
means that Async API returns a future list of values.
The list is a collection of elements in dart programming.
We have manually converted from one type to another type.
How do you convert Future List to List in flutter?
dart async package provides classes for async and awaits operations.
Created async function and converted a Future List using Future.value(). In real-time, this gets the 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])
Call the future list using await returns list.
Here is a 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 do you convert List to Future of List in flutter?
First, You have a list is created with initializing syntax. Created a Future object using the Future.value() method by passing the list.
Here is 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
To summarize, We can easily convert List
to Future<List>
and Future<List>
to List
with examples.