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

Flutter中将接口返回JSON存储到Map<String,Profile>出现类型错误如何修复

问题根因

你当前代码的错误核心是遍历对象层级错了:

  • randomuser.me返回的根JSON对象第一层只有results等少数键,extractedData.forEach遍历的时候,拿到的第一个键是字符串"results",对应的value是存储所有用户数据的数组
  • 你直接拿数组对象去访问value['login'],数组下标要求是int类型,你传入了字符串'login',直接触发类型不匹配错误。
适配现有写法的修复方案

直接修改fetchData方法中的遍历逻辑,替换原来的遍历根对象的代码即可,改动最小,完全保留你原有的赋值逻辑:

Future<void> fetchData() async {
  final url = Uri.parse('https://randomuser.me/api/?results=50');
  final response = await http.get(url);
  final extractedData = json.decode(response.body);
  Map<String, Profile> map = {};
  // 先取results数组,判断不为空再遍历
  final List<dynamic> userList = extractedData['results'] ?? [];
  for (var user in userList) {
    // 用username作为Map的key,也可以换成user['login']['uuid']保证全局唯一
    final String username = user['login']['username'];
    map.putIfAbsent(username, () => Profile(
      userName: username,
      name: user['name']['first'],
      emailId: user['email'],
      timePeriod: user['registered']['age'] as int,
      age: user['dob']['age'] as int,
      nationality: user['nat'],
      number: user['cell'],
      streetNumber: user['location']['street']['number'] as int,
      streetName: user['location']['street']['name'],
      city: user['location']['city'],
      country: user['location']['country'],
      // 兼容部分地区postcode返回字符串的情况,避免类型错误
      postCode: (user['location']['postcode'] as num).toInt(),
      picture: user['picture']['large']
    ));
  }
  _data = map;
  notifyListeners();
}
可选优化方案(更易维护)

给Profile类增加fromJson工厂构造方法,拆分解析逻辑,后续字段调整时修改更集中:

// 在Profile类中新增如下代码
factory Profile.fromJson(Map<String, dynamic> json) {
  return Profile(
    userName: json['login']['username'],
    name: json['name']['first'],
    emailId: json['email'],
    timePeriod: json['registered']['age'] as int,
    age: json['dob']['age'] as int,
    nationality: json['nat'],
    number: json['cell'],
    streetNumber: json['location']['street']['number'] as int,
    streetName: json['location']['street']['name'],
    city: json['location']['city'],
    country: json['location']['country'],
    postCode: (json['location']['postcode'] as num).toInt(),
    picture: json['picture']['large']
  );
}

调整后fetchData的遍历逻辑可以简化为:

for (var user in userList) {
  final profile = Profile.fromJson(user);
  map[profile.userName] = profile;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 15:24:03