Flutter: BitmapDescriptor.fromAsset deprecated

Issue

I’m new to Flutter and I have this code in my app that works perfect to populate a markers list with thousands of items having each of them one of 4 available icons stored locally as png files:

        for (var bla in jData) {
          LatLng _markerPos =
            LatLng(
              double.parse(bla['lat']),
              double.parse(bla['lng'])
            );
          String _iconImage = 'assets/images/' + bla['q'].toString() + '.png';
          markers.add(Marker(
            position: _markerPos,
            markerId: MarkerId(bla['hash']),
            icon: BitmapDescriptor.fromAsset(_iconImage)
          ));
        }

But now the fromAsset method has been deprecated and the new way to assign a BitmapDescriptor seems to be through a Future function which throws an error* (Also sounds to me like a lot of trouble for something that can be done so easily the old way).

So could anyone please help me achieve this with the new method fromAssetImage? It seems weird to me to assign a Future inside a for loop but I’m a noob.

This is the error I get with the new method*: The argument type ‘Future’ can’t be assigned to the parameter type ‘BitmapDescriptor’. (argument_type_not_assignable at [flutter_app] lib/lash.dart:81)

Solution

Yes, the fromAsset method was a synchronous call to get a Bitmap object, but now it has been replaced by the fromAssetImage asynchronous method, I guess it is because of responsiveness and performance-related issues.

Although it looks like it is a new topic for you, it should be easy to get your piece of code working with asynchronous programming, you just need to tag your loop as async, and then await the fromAssetImage object return before using it in your marker. Something like this should work, although I have not tried it.

         for (var bla in jData) async {
          LatLng _markerPos =
            LatLng(
              double.parse(bla['lat']),
              double.parse(bla['lng'])
            );
          String _iconImage = 'assets/images/' + bla['q'].toString() + '.png';
          final bitmapIcon = await BitmapDescriptor.fromAsset(_iconImage);
          markers.add(Marker(
            position: _markerPos,
            markerId: MarkerId(bla['hash']),
            icon: bitmapIcon
          ));
        }

Answered By – drogel

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *