Flutter开发遇type 'double' is not a subtype of type 'int'报错如何解决
错误原因
这个报错的核心原因是你处理dynamic类型的天气数据时,没有对weatherData['main']['temp']的返回值做类型兼容处理:不同天气接口返回的温度字段可能是int也可能是double类型,你直接将dynamic类型的值赋值给double类型的temp2时,如果接口返回的是int就会触发类型不匹配错误。
修复方案
1. 兼容int/double的温度类型处理
修改updateData方法里的温度取值逻辑,先用通用数字类型num接收温度值,再做后续处理,同时给字符串类型字段加toString()兜底,避免其他类型不匹配问题:
void updateData(dynamic weatherData) { // num类型同时兼容int和double,避免类型冲突 num tempNum = weatherData['main']['temp']; temp = tempNum.round(); cityName = weatherData['name'].toString(); print(temp); print(cityName); }
2. 优化late变量的加载逻辑(可选,避免其他潜在崩溃)
你当前用了late修饰的变量,万一数据还没初始化完成就触发build会抛出LateInitializationError,建议加加载状态判断:
首先在State类中新增加载状态标记:
late String cityName; late int temp; // 新增加载状态 bool isLoading = true;
修改updateData方法,数据处理完成后更新状态:
void updateData(dynamic weatherData) { num tempNum = weatherData['main']['temp']; temp = tempNum.round(); cityName = weatherData['name'].toString(); setState(() { isLoading = false; }); }
修改build方法,加载时显示进度指示器,加载完成再显示天气内容:
@override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: Center( child: isLoading ? const CircularProgressIndicator() : Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( cityName, style: const TextStyle(fontSize: 30.0), ), const SizedBox(height: 20.0), Text( '$temp°', style: const TextStyle(fontSize: 30.0), ), ], ), ), ), ); }
额外优化建议
- 尽量避免用
dynamic类型传递接口数据,建议定义专门的天气数据实体类,序列化时就完成类型校验,能提前规避绝大多数运行时类型错误 - 对接口返回的字段增加空值判断,避免接口返回空值时触发空安全异常
内容的提问来源于stack exchange,提问作者Daniel Kim
相关产品推荐
相关产品推荐

