Flutter调用randomuser.me API解析数据时出现String非int子类型错误
错误成因
这个报错的核心原因是你对API返回的JSON结构理解有误,遍历逻辑完全错配:
- 调用
json.decode得到的顶层extractedData是一个Map,结构为{"results": [用户1, 用户2...], "info": {...}},你直接遍历这个顶层Map的键值对,第一次遍历到key="results"时,对应的value就是存储所有用户数据的数组(List类型) - 你在代码中尝试对这个List类型的value执行
value['results']操作,List的下标只能是int类型,你传入了String类型的key,就触发了type 'String' is not a subtype of type 'int' of 'index'的报错 - 额外的问题:你直接用点语法(比如
.login.username)访问动态类型的JSON字段,Dart的dynamic类型不支持直接用点语法访问嵌套JSON属性,必须用方括号[]逐层取值
修复方案
把fetchData方法里的遍历逻辑完全替换,正确遍历results数组即可,修改后的代码如下:
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); // 先拿到用户数组 final List userList = extractedData['results']; Map<String, Profile> map = {}; // 遍历用户数组 for (var user in userList) { // 用用户的uuid作为map的唯一key String userId = user['login']['uuid']; map.putIfAbsent(userId, () => Profile( userName: user['login']['username'], name: user['name']['first'], emailId: user['email'], timePeriod: user['registered']['age'], age: user['dob']['age'], nationality: user['nat'], number: user['cell'], streetNumber: user['location']['street']['number'], 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(); }
如果后续想更稳妥的处理JSON解析,建议用json_serializable库自动生成序列化代码,避免手动写key拼写错误或者类型不匹配的问题。
内容的提问来源于stack exchange,提问作者coolhack7
相关产品推荐
相关产品推荐

