Search code examples
google-mapsflutterdartflutter-alertdialog

Update marker in Google maps alertdialog in flutter


I am trying to load googlemap(google_maps_flutter 0.5.25+1 library) on a dialog window using the following method

_loadMapDialog() {
try {
  if (_currentPosition.latitude == null) {
    Toast.show("Location not available. Please wait...", context,
        duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
    _getLocation(); //_getCurrentLocation();
    return;
  }
  _controller = Completer();
  _userpos = CameraPosition(
    target: LatLng(latitude, longitude),
    zoom: 14.4746,
  );

  markers.add(Marker(
      markerId: markerId1,
      position: LatLng(latitude, longitude),
      infoWindow: InfoWindow(
        title: 'New Location',
        snippet: 'Delivery Location',
      )));

  showDialog(
    context: context,
    builder: (context) {
      return StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
          return AlertDialog(
            title: Text("Select Your Location"),
            titlePadding: EdgeInsets.all(5),
            content: Text(curaddress),
            actions: <Widget>[
              Container(
                height: screenHeight / 1.4 ?? 600,
                width: screenWidth ?? 400,
                child: 
                GoogleMap(
                  mapType: MapType.normal,
                  initialCameraPosition: _userpos,
                  markers: markers,
                  onMapCreated: (controller) {
                    _controller.complete(controller);
                  },
                  onTap: _loadLoc,
              ),
              )
            ],
          );
        },
      );
    },
  );
} catch (e) {
  print(e);
  return;
}


 }

      void _loadLoc(LatLng loc) async{
        setState(() {
          print("insetstate");
          markers.clear();
          latitude = loc.latitude;
          longitude = loc.longitude;
          label = latitude.toString();
          _getLocationfromlatlng(latitude,longitude);
          _home = CameraPosition(
            target: loc,
            zoom: 14,
          );
          markers.add(Marker(
              markerId: markerId1,
              position: LatLng(latitude, longitude),
              infoWindow: InfoWindow(
                title: 'New Location',
                snippet: 'Delivery Location',
              )));

        });
        _userpos = CameraPosition(
            target: LatLng(latitude, longitude),
            zoom: 14.4746,
          );
        _newhomeLocation();
      }

      Future<void> _newhomeLocation() async {
        gmcontroller = await _controller.future;
        gmcontroller.animateCamera(CameraUpdate.newCameraPosition(_home));
        Navigator.of(context).pop(false);
        _loadMapDialog();
      }

I did manage to load the map in my AlertDialog. The problem is I need to be able to select new location on the map remove the previous marker and show new marker on the map, however marker is not showing on the map unless the app perform hot reload. For now I'm using kind a stupid way which pop the current alertdialog and show it again using _loadMapDialog() method to reload widget. I did try to use flutter_places_dialog library but seems I got some problem with activity return result error.

flutter newb here be kind..


Solution

  • Problem is you are updating marker with setState provided by StatefulWidget. But Dialog is updating its state with setState provided by StatefulBuilder.

    Solution is add StatefulBuilder's setState to onTap callback function's parameter and use it inside _loadLoc function like my code.

    List<Marker> markers = [];
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text('GoogleMap'),
        ),
        body: Center(
          child: RaisedButton(
            onPressed: () {
              showDialog(
                context: (context),
                builder: (context) {
                  return StatefulBuilder(builder: (context, newSetState) {
                    return AlertDialog(
                      title: Text('Google Map'),
                      content: GoogleMap(
                        initialCameraPosition: CameraPosition(
                            target: LatLng(11.004556, 76.961632), zoom: 14),
                        markers: markers.toSet(),
                        onTap: (newLatLng) {
                          addMarker(newLatLng, newSetState);
    
                        },
                      ),
                    );
                  });
                });
          },
        ),
      ),
    );
    
    addMarker(latLng, newSetState)
    {
      newSetState(() {
        markers.clear();
        markers.add(Marker(markerId: MarkerId('New'), position: latLng));
      });
    }