How to display images, received from an API response in flutter?

Ayush Shekhar picture Ayush Shekhar · Oct 31, 2018 · Viewed 16k times · Source

I am using the http Dart package to send a GET request to the MapQuest Static Maps API to obtain an image. However, the response to this request directly returns an image, and not a Uri, or maybe I am doing something wrong.

Can you please help me display the received image?

Here's the request Code:

 final http.Response response = await http.get(
    'https://www.mapquestapi.com/geocoding/v1/address?key=[MYAPIKEY]&inFormat=kvp&outFormat=json&location=${address}&thumbMaps=false&maxResults=1');

final decodedResponse = json.decode(response.body);
setState(() {
  _coords = decodedResponse['results'][0]['locations'][0]['latLng'];
});
 final http.Response staticMapResponse = await http.get(
        'https://www.mapquestapi.com/staticmap/v5/map?key=[MYAPIKEY]&center=${coords['lat']},${coords['lng']}&zoom=13&type=hyb&locations=${coords['lat']},${coords['lng']}&size=500,300@2x');

The coordinates are received from the Geocoding API of MapQuest which is an async request.

Answer

Ayush Shekhar picture Ayush Shekhar · Oct 31, 2018

As suggested by Günter Zöchbauer I included the Request Url directly in my Image.network() widget and it worked.

Here's the Code:

void getStaticMapCoordinates(String address) async {
    if (address.isEmpty) {
      return;
    }

    final http.Response response = await http.get(
        'https://www.mapquestapi.com/geocoding/v1/address?key=[APIKEY]&inFormat=kvp&outFormat=json&location=${address}&thumbMaps=false&maxResults=1');

    final decodedResponse = json.decode(response.body);
    setState(() {
      _coords = decodedResponse['results'][0]['locations'][0]['latLng'];
    });
  }

  Widget _buildStaticMapImage() {

    if(_coords == null) {
      return Image.asset('assets/product.jpg');
    }
    return FadeInImage(
      image: NetworkImage(
          'https://www.mapquestapi.com/staticmap/v5/map?key=[APIKEY]&center=${_coords['lat']},${_coords['lng']}&zoom=13&type=hyb&locations=${_coords['lat']},${_coords['lng']}&size=500,300@2x'),
      placeholder: AssetImage('assets/product.jpg'),
    );
  }

The getStaticMapCoordinates function executes everytime the user changes the address field and as a result of setState, the Image Widget re-renders.