I am trying to load dynamically icons on google map, the below example works fine. However when Im trying to run it as a method that returns BitMapDescriptor then I am facing this error:
Unhandled Exception: type 'Null' is not a subtype of type 'BitmapDescriptor' Any ways I can fix this?
This works:
void customMarker(int index) {
BitmapDescriptor.fromAssetImage(ImageConfiguration(size: Size(20, 20)),
'assets/images/route_markers/$index.png')
.then((res) {
_pinLocationIcon = res;
});
}
@override
void initState() {
super.initState();
customMarker(1);
getCurrentLocation();
}
and put _pinLocationIcon as an icon in loop.
Doesn't work :
for (var i = 0; i < markers.length; i ) {
final marker = Marker(
markerId: MarkerId(markers[i].id),
position: 53, 22),
icon: customMarker(i),
onTap: () {},
);
}
BitmapDescriptor customMarker(int index) {
var data;
BitmapDescriptor.fromAssetImage(ImageConfiguration(size: Size(20, 20)),
'assets/images/items/$index.png')
.then((res) {
data = res;
});
return data;
}
CodePudding user response:
The method BitmapDescriptor.fromAssetImage is asynchronous, that's why you are calling .then on the method, it means that the value can be returned at any time, not in the order of the code written.
The code inside then((res){... will set the value for the variable data after data was already returned with a null value, so you won't get your icon.
You need to learn how to use asynchronous methods, in this case, you would need to make those methods async, and await for the image to load before returning. Try this:
@override
void initState() {
super.initState();
loadMarkers();
getCurrentLocation();
}
void loadMarkers() async { // Notice the async keyword
for (var i = 0; i < markers.length; i ) {
final marker = Marker(
markerId: MarkerId(markers[i].id),
position: 53, 22),
icon: await customMarker(i), //Notice the await here
onTap: () {},
);
}
}
BitmapDescriptor customMarker(int index) async { //Notice Async and Await again
var data = await BitmapDescriptor.fromAssetImage(
ImageConfiguration(size: Size(20, 20)),
'assets/images/items/$index.png'
);
return data;
}
