如何显示从 API 响应中接收到的图像?

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

我正在使用 http Dart package 向 MapQuest 静态地图 API 发送 GET 请求以获取图像。但是,这个请求的响应直接是returns一张图片,而不是一张Uri,或者我做错了什么。

你能帮我显示收到的图像吗?

请求代码如下:

 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');

坐标是从 MapQuest 的地理编码 API 接收的,这是一个 async 请求。

如果图片是您的 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))    
    //...

如果需要解析:

  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');
  }

根据 Günter Zöchbauer 的建议,我将请求 Url 直接包含在我的 Image.network() 小部件中并且它起作用了。

代码如下:

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'),
    );
  }

每次用户更改地址字段时都会执行 getStaticMapCoordinates 函数,并且作为 setState 的结果,Image Widget 会重新呈现。

我使用 Image class 从响应主体以字节流形式创建内存中图像对象。

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

现在您可以直接在您的组件中加载此图像。

您可以将 header 添加到 NetworkImage 小部件,例如: NetworkImage( "你的端点 URL ", headers: {header:value}) link 下方有更多信息。
https://api.flutter.dev/flutter/widgets/Image/Image.network.html

有时使用复杂的 header 从 URL 获取图像很麻烦。所以那时,我们可以直接在 NetworkImage 小部件中使用 header 地图,它就像一个魅力-

        .
        .
    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;
  }