You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter从RestApi获取图片并在CircleAvatar显示问题求助

解决从RestAPI获取图片并在CircleAvatar中显示的问题

你的代码里有两个核心问题导致图片无法显示,直接修正如下:

1. 修正图片获取方法getProfileImg

你错误地用NetworkAssetBundle去加载response.body——这完全没必要,服务器返回的response.bodyBytes已经是图片的原始字节数组,直接返回它就行。另外注意几个细节:

  • Image.memory需要的是Uint8List类型,response.bodyBytes本身就是这个类型,无需额外转换
  • 去掉请求头里多余的Content-Type: application/json(GET请求获取图片不需要这个)
  • 修正Authorization头的格式,去掉Bearer前面的空格

修正后的代码:

Future<Uint8List> getProfileImg() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  final String? accessToken = prefs.getString('accessToken');
  print(accessToken);
  
  final response = await http.get(
    Uri.parse(RestClient.getProfileImage),
    headers: {
      'Authorization': 'Bearer $accessToken',
    },
  );

  if (response.statusCode == 200) {
    return response.bodyBytes;
  } else {
    print(response.statusCode);
    throw Exception('Failed to get profile image');
  }
}

2. 用FutureBuilder处理异步加载

getProfileImg是异步方法,不能直接把Future对象传给Image.memory,必须用FutureBuilder等待数据加载完成后再渲染:

方式一:把图片作为CircleAvatar的child

Widget buildProfileImage() => CircleAvatar(
      radius: profileHeight / 2,
      backgroundColor: Colors.grey.shade800,
      child: FutureBuilder<Uint8List>(
        future: getProfileImg(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return Image.memory(
              snapshot.data!,
              fit: BoxFit.cover,
              width: profileHeight,
              height: profileHeight,
            );
          } else if (snapshot.hasError) {
            return Icon(Icons.error, color: Colors.red);
          } else {
            return CircularProgressIndicator(color: Colors.white);
          }
        },
      ),
    );

方式二:把图片作为CircleAvatar的背景图(更贴合组件用法)

Widget buildProfileImage() => FutureBuilder<Uint8List>(
      future: getProfileImg(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return CircleAvatar(
            radius: profileHeight / 2,
            backgroundColor: Colors.grey.shade800,
            backgroundImage: MemoryImage(snapshot.data!),
          );
        } else if (snapshot.hasError) {
          return CircleAvatar(
            radius: profileHeight / 2,
            backgroundColor: Colors.grey.shade800,
            child: Icon(Icons.error, color: Colors.red),
          );
        } else {
          return CircleAvatar(
            radius: profileHeight / 2,
            backgroundColor: Colors.grey.shade800,
            child: CircularProgressIndicator(color: Colors.white),
          );
        }
      },
    );

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 07:53:31