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

5

8

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.

Inherited answered 31/10, 2018 at 13:47 Comment(4)
To displaying image from an api: flutter.io/cookbook/images/network-imageBate
I have tried using Image.network(), the point is that it takes a String value for the url of the image, which I don't receive from the GET request.Inherited
Just pass the string you pass to the GET request to NetworkImage and NetworkImage will make the GET request for you. Otherwise use docs.flutter.io/flutter/widgets/Image/Image.memory.htmlLammas
@GünterZöchbauer Thanks a lot!! Directly passing in the Request Url in Image.network() worked.Inherited
I
5

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.

Inherited answered 31/10, 2018 at 14:37 Comment(1)
What there is an header in the request?Midwife
T
6

I used Image class to create an in-memory image object from the response body in a byte stream form.

var _profileImage = Image.memory(response.bodyBytes).image;

Now you can directly load this image in your component.

Troat answered 18/7, 2020 at 5:40 Comment(1)
im trying to create a image view that gets up to 4 images and should wait for them all to finish loading before displaying anything i think this will help for thisTwombly
I
5

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.

Inherited answered 31/10, 2018 at 14:37 Comment(1)
What there is an header in the request?Midwife
A
2

Sometimes fetching image from URL with complex headers are cumbersome. So at that time, we can use the header map directly in the NetworkImage widget and it works like a charm-

        .
        .
    child: CircleAvatar(
            backgroundImage:
            NetworkImage("www.mypropic.com",headers:getTokenHeaders());)
        .
        . 

    static Map<String, String> getTokenHeaders() {
    Map<String, String> headers = new Map();
    headers['Authorization'] = _bearerToken!;
    headers['content-type'] = 'application/json';
    return headers;
  }
Ahern answered 23/7, 2021 at 5:15 Comment(0)
S
1

If a image is the repose from your URL:

//...
    child: new ClipRRect(
         borderRadius: new BorderRadius.circular(30.0),
         child: Image.network('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', 
                              fit: BoxFit.cover, 
                              height: 60.0, width: 60.0))    
    //...

if you need to parse:

  final response = 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');

  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON
    return json.decode(response.body)["imageURL"]; //  <------- DO THE PARSING HERE AND THEN PASS THE URL TO THE ABOVE EXAMPLE
  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
Sapers answered 31/10, 2018 at 14:11 Comment(1)
Thanks for your response but the API doesn't return the image url in Json. It returns the image. For reference: developer.mapquest.com/documentation/static-map-api/v5Inherited
M
0

You can add the headers to the NetworkImage widget like : NetworkImage( "your endpoint URL ", headers: {header:value}) Below link has more information.
https://api.flutter.dev/flutter/widgets/Image/Image.network.html

Magyar answered 14/8, 2020 at 2:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.