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

Flutter:不使用Future Builder从API获取并展示用户数据

解决Flutter单用户API数据展示问题

问题分析

  • getUser()函数逻辑错误:API返回单用户数据,却用了处理列表的map方法,最后还转成字符串,无法得到可用的User对象。
  • 未使用异步状态管理组件处理API请求的异步过程,导致数据无法渲染到UI。

修正步骤

1. 修复getUser()函数

调整为返回Future<User>类型,直接解析单用户数据:

Future<User> getUser() async {
  var response = await http.get(Uri.parse(url));
  if (response.statusCode == 200) {
    var jsonData = jsonDecode(response.body);
    return User.fromJson(jsonData['data']); // 单用户直接解析,无需map
  } else {
    throw Exception('加载用户数据失败');
  }
}

2. 用FutureBuilder渲染动态数据

通过FutureBuilder处理异步请求的不同状态,将数据绑定到UI:

FutureBuilder<User>(
  future: getUser(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return Center(child: CircularProgressIndicator());
    } else if (snapshot.hasError) {
      return Center(child: Text('错误: ${snapshot.error}'));
    } else if (snapshot.hasData) {
      User user = snapshot.data!;
      return Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(12))
        ),
        padding: EdgeInsets.only(left: 10, right: 10),
        height: 120,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            CircleAvatar(
              radius: 28,
              backgroundImage: NetworkImage(user.avatar),
            ),
            Text(
              user.name, // 替换为你的User模型对应字段
              style: TextStyle(fontSize: 17, color: Colors.black),
            ),
            Icon(
              Icons.arrow_forward_ios,
              color: Colors.grey,
            ),
          ],
        ),
      );
    } else {
      return Center(child: Text('无用户数据'));
    }
  },
)

3. 确保User模型字段匹配API返回

User类的fromJson方法要和API返回的字段一一对应:

class User {
  final String avatar;
  final String name;
  // 其他字段根据API返回定义

  User({required this.avatar, required this.name});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      avatar: json['avatar'],
      name: json['name'], // key需与API返回字段一致
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 04:55:19