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 ?
CodePudding user response:
I would consider reworking the class so that the static method creates an instance of Example
, rather than the constructor calling the static method.
class Example {
List<int> abc;
Example(this.abc);
static Future<Example> fill() async {
return Example(await Future.delayed(const Duration(seconds: 2), () {
return [1, 2, 3];
}));
}
}
void main() async {
print((await Example.fill()).abc);
}
The MapMarker
example can be updated in the same way.
class MapMarker extends ChangeNotifier {
List<Location> locationsList;
MapMarker(this.locationsList);
static Future<MapMarker> getMapMarkerWithLocations() async {
return MapMarker(await LocationsDatabase.instance.getAllLocations());
}
}
But since you are using a ChangeNotifier
why not simply add a call to notifyListeners()
?
class MapMarker extends ChangeNotifier {
List<Location> locationsList = [];
MapMarker() {
LocationsDatabase.instance.getAllLocations().then((value) {
locationsList = value;
notifyListeners();
});
}
}
CodePudding user response:
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;
}
}