You need to enable JavaScript to run this app. Flutter/Dart调用API路由GET请求响应body无返回 需在GridView Builder展示缩略图
优惠活动
大模型
产品
解决方案
定价
更多

Flutter/Dart调用API路由GET请求响应body无返回 需在GridView Builder展示缩略图

问题根因

http.Request.send()返回的是http.StreamedResponse流式响应对象,该对象没有封装好的body属性,直接读取response.body属于无效调用,因此无法获取到接口返回内容。

修复代码

适配现有写法的修改方案

仅需补充流式响应转字符串的逻辑即可:

Future<List<Photo>> fetchPhotos(http.Client client) async {
  var headers = {
    'Authorization': 'Bearer $bearer_token'
  };
  var request = http.Request('GET', Uri.parse('https://xxxxx.execute-api.us-east-2.amazonaws.com/stg/assets'));

  request.headers.addAll(headers);

  http.StreamedResponse response = await request.send();

  if (response.statusCode == 200) {
    // 流式响应转字符串,获取接口返回的完整内容
    String responseBody = await response.stream.bytesToString();
    return compute(parsePhotos, responseBody);
  }
  else {
    print(response.reasonPhrase);
    return [];
  }
}

简化写法

可以直接使用http.get方法,无需手动处理流式响应:

Future<List<Photo>> fetchPhotos(http.Client client) async {
  var headers = {
    'Authorization': 'Bearer $bearer_token'
  };
  final response = await client.get(
    Uri.parse('https://xxxxx.execute-api.us-east-2.amazonaws.com/stg/assets'),
    headers: headers,
  );

  if (response.statusCode == 200) {
    return compute(parsePhotos, response.body);
  } else {
    print(response.reasonPhrase);
    return [];
  }
}
GridView展示缩略图说明

确保parsePhotos方法已正确解析接口返回的JSON结构,将每个条目对应的缩略图URL字段赋值给Photo类的对应属性,GridView实现参考:

GridView.builder(
  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
    crossAxisCount: 2,
    crossAxisSpacing: 4,
    mainAxisSpacing: 4,
  ),
  itemCount: photos.length,
  itemBuilder: (context, index) {
    return Image.network(
      photos[index].thumbnailUrl,
      fit: BoxFit.cover,
    );
  },
)

内容的提问来源于stack exchange,提问作者user2349088

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 07:51:03