skip to Main Content

I wanted to add some markers in a gmap on flutter I made. I tried this code but it doesn’t work. I have added link in pubspec and picture is in assets too.

Future<void> addMarker(
      LatLng mLatLng, String mTitle, String mDescription) async {
    BitmapDescriptor markerbitmap = await BitmapDescriptor.fromAssetImage(
      ImageConfiguration(),
      "assets/images/icons/pin.png",
    );
    setState(() async {
      _markers.clear();

      _markers.add(Marker(
          markerId:
              MarkerId((mTitle + "_" + _markers.length.toString()).toString()),
          position: mLatLng,
          infoWindow: InfoWindow(
            title: mTitle,
            snippet: mDescription,
          ),
          icon: markerbitmap //BitmapDescriptor.defaultMarker,
          ));
    });
  }

no marker gets addded on the map but shows this error in debug console

[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception:
setState() callback argument returned a Future. E/flutter ( 7655): The
setState() method on _HomePageState#3d9e4 was called with a closure or
method that returned a Future. Maybe it is marked as "async".
E/flutter ( 7655): Instead of performing asynchronous work inside a
call to setState(), first execute the work (without updating the
widget state), and then synchronously update the state inside a call
to setState(). E/flutter ( 7655): #0 State.setState. package:flutter/…/widgets/framework.dart:1112 E/flutter (
7655): #1 State.setState
package:flutter/…/widgets/framework.dart:1128 E/flutter ( 7655): #2
_HomePageState.addMarker package:mymapp/screens/home_page.dart:417 E/flutter ( 7655): E/flutter ( 7655):
E/MethodChannel#plugins.flutter.dev/google_maps_android_0( 7655):
Failed to handle method call

3

Answers


  1. Chosen as BEST ANSWER

    I DID THIS. First, create a method that handles the asset path and receives a size (this can be either the width, height, or both, but using only one will preserve ratio).

    import 'dart:ui' as ui;
    
    Future<Uint8List> getBytesFromAsset(String path, int width) async {
      ByteData data = await rootBundle.load(path);
      ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(), targetWidth: width);
      ui.FrameInfo fi = await codec.getNextFrame();
      return (await fi.image.toByteData(format: ui.ImageByteFormat.png)).buffer.asUint8List();
    }
    

    Then, just add it to your map using the right descriptor:

       final Uint8List markerIcon = await getBytesFromAsset('assets/images/flutter.png', 100);
        final Marker marker = Marker(icon: BitmapDescriptor.fromBytes(markerIcon));
    

    REF: How to change the icon size of Google Maps marker in Flutter?


  2. You should do this in initState

     
     final _controller = Completer<GoogleMapController>();
    
     var _markers = const <Marker>{};
      Set<Marker> get markers => _markers;
      set markers(Set<Marker> val) {
        setState(() => _markers = val);
      }
    
    ...
    
      @override
      void initState() {
        initializeMap();
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: GoogleMap(
            ...
            markers: markers,
            ...
            onMapCreated: (GoogleMapController controller) {
              _controller.complete(controller);
            },
          ),
        );
      }
    
    ...
    
    void initializeMap(){
     markers = {
         Marker(
           markerId: MarkerId(UniqueKey().toString()),
           icon: await BitmapDescriptor.fromAssetImage(
             const ImageConfiguration(),
             'assets/images/icons/pin.png',
           ),
           position: target.target,
           rotation: target.tilt,
         )
       };
    }
    
    
    Login or Signup to reply.
  3. you have this error because you are trying to use "Async" in the block of a setState.

    you can remove the async and modify your code to this:

    Future<void> addMarker(
          LatLng mLatLng, String mTitle, String mDescription) async {
        BitmapDescriptor markerbitmap = await BitmapDescriptor.fromAssetImage(
          ImageConfiguration(),
          "assets/images/icons/pin.png",
        );
        setState(() *** ----- delete the async here {
          _markers.clear();
    
          _markers.add(Marker(
              markerId:
                  MarkerId((mTitle + "_" + _markers.length.toString()).toString()),
              position: mLatLng,
              infoWindow: InfoWindow(
                title: mTitle,
                snippet: mDescription,
              ),
              icon: markerbitmap //BitmapDescriptor.defaultMarker,
              ));
        });
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search