'intial class variable with async function result dart
Hello Im working on flutter app using changenotifier for state managment
In fact Im trying to intialize a list with async function result
but I get this error:
Uncaught Error: TypeError: Instance of '_Future<dynamic>': type '_Future<dynamic>' is not a subtype of type 'List<Location>'
class MapMarker extends ChangeNotifier{
List<Location> locationsList = [];
MapMarker(){
LocationsDatabase.instance.getAllLocations().then((value) => locationsList=value);
}
static getAllLocations() {
List<Location> a = await LocationsDatabase.instance.getAllLocations();
return a
}
}
any ideas how to do that ?
Solution 1:[1]
Small change on you code
class Example {
Future<List<int>>? abc = null;
Example() {
initial();
}
initial() async {
abc = fill();
}
static Future<List<int>> fill() async {
return await Future.delayed(const Duration(seconds: 2), () {
return [1, 2, 3];
});
// return [];
}
}
main() async {
print((await Example().abc));
}
output:
[1, 2, 3]
Maper
class MapMarker extends ChangeNotifier{
Future<List<Location>>? locationsList = null;
MapMarker(){
initial();
}
initial() async {
locationsList = fill();
}
static Future< List<Location>> getAllLocations() async {
List<Location> a = await LocationsDatabase.instance.getAllLocations();
return a;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
