Reputation: 12455
I added the markers to googlemap.
In this code. At the first load, there is no markers
When I push r
for hot reload , markers appear
I just guess,, I might have to do something here???
setState((){
print("items ready and set state");
});
How can I solve this??
class _MapPageState extends State<MapPage> {
Completer<gmap.GoogleMapController> _controller = Completer();
Set<gmap.Marker> _markers = {};
@override
void initState(){
super.initState();
_asyncMethod();
print("init ready");
}
_asyncMethod() async {
_markers = {};
print ("asyncMethod start");
List<dynamic> wayLabels = annotModel['wayLabel'];
wayLabels.forEach((x){
gmap.BitmapDescriptor icon;
gmap.BitmapDescriptor.fromAssetImage(
ImageConfiguration(devicePixelRatio: 2.5),
x['image'][CommonFunc.langKey]).then((onValue) {
icon = onValue;
gmap.Marker marker = gmap.Marker(
markerId: gmap.MarkerId(x['title']),
position: gmap.LatLng(x['latitude'],x['longitude']),
icon: icon
);
_markers.add(marker);
});
});
setState((){
print("items ready and set state");
});
}
Widget makeMyMap(){
gmap.GoogleMap myMap = gmap.GoogleMap(
mapType: gmap.MapType.normal,
markers : _markers,
initialCameraPosition: _kGooglePlex,
onMapCreated: (gmap.GoogleMapController controller) {
_controller.complete(controller);
}
);
return Container(child:myMap);
}
@override
Widget build(BuildContext context){
return
Column(children: <Widget>[
Expanded(child:Stack(children: <Widget>[
makeMyMap(),
]),),
]);
}
}
gmap.BitmapDescriptor.fromAssetImage
might takes time so
setState((){
print("items ready and set state");
});
in _asyncMethod()
was called before every markers are set.
That was the problem.
Solution.
change _markers.add(marker);
to
setState((){
_markers = markers;
print("items ready and set state");
});
it works well.
Upvotes: 1
Views: 1527
Reputation: 142
You should try using this package https://pub.dev/packages/after_layout. Call _asyncMethod inside afterFirstLayout method
@override
void afterFirstLayout(BuildContext context) {
// Calling the same function "after layout" to resolve the issue.
_asyncMethod();
}
also, i think is healthier to assign the markers in _asyncMethod to a local variable an then in the setState change the markers
_asyncMethod() async {
var localMarkers = {};
.
.
.
setState((){
_markers = localMarkers;
});
}
Upvotes: 1