Flutter调用本地Flask API时出现type 'null'类型转换错误
问题解决:Flutter真机调用本地Flask API出现类型转换错误
核心错误原因
你的Flask API返回的JSON结构外层包含data和message字段,学生的具体信息嵌套在data对象中,但你的代码直接将整个JSON响应对象传给Student.fromJson,导致json['nome']无法找到对应值,返回null,触发type 'null' is not a subtype of type String in type cast错误。
修正方案
1. 修改API数据解析逻辑
在fetchStudent方法中,先提取出data字段对应的对象,再传给Student.fromJson:
Future<Student> fetchStudent() async { // 真机必须替换为电脑的局域网IP(如192.168.1.105),10.0.2.2仅适用于安卓模拟器 final Uri url = Uri.parse('http://你的电脑局域网IP:5000/diario/aluno/240'); final response = await http.get(url); print('API Response: ${response.body}'); if (response.statusCode == 200) { // 取出嵌套在data中的学生数据 final studentData = jsonDecode(response.body)['data'] as Map<String, dynamic>; final student = Student.fromJson(studentData); return student; } else { throw Exception('Failed to load student'); } }
2. 真机访问的关键注意事项
- 替换IP地址:
10.0.2.2是安卓模拟器专属的本地映射地址,真机无法识别,必须换成电脑的局域网IP(可通过电脑网络设置查看)。 - 网络环境:确保电脑和真机连接在同一个WiFi网络下。
- 端口连通性:如果使用
adb reverse tcp:5000 tcp:5000,真机可以通过http://localhost:5000访问,但局域网IP方式更稳定。
为什么之前的空值处理无效
你尝试的name: json['nome'] as String? ?? 'there is no such name'之所以没用,是因为传入fromJson的是整个外层JSON对象,json['nome']本身就是null,自然只能显示默认值,根本没访问到data内部的真实nome字段。
内容的提问来源于stack exchange,提问作者José Carlos
相关产品推荐
相关产品推荐

