Flutter天气应用出现类型转换异常,无法获取天气数据求助
问题解决:type 'double' is not a subtype of type 'Iterable' 异常
错误原因
报错根源在getData()方法构造Uri时,传递的lat和lon参数是double类型,但Uri.https的query参数要求值必须是String或Iterable<String>类型,直接传入double会触发类型不匹配异常。
修复步骤
将latitood和longitood这两个double类型变量转换为字符串后,再传入Uri的query参数中。
修复后的getData()代码
void getData() async { Uri uri = Uri.https( 'api.openweathermap.org', '/data/2.5/weather', { 'lat': latitood.toString(), // 转换为字符串 'lon': longitood.toString(), // 转换为字符串 'appid': myAPI }, ); http.Response response = await http.get(uri); print(response.statusCode); if (response.statusCode == 200) { String data = response.body; var decodedData = jsonDecode(data); int weatherCondition = decodedData['weather'][0]['id']; print(weatherCondition); double temperature = decodedData['main']['temp']; print(temperature); String cityName = decodedData['name']; print(cityName); } else { print(response.statusCode); } }
额外优化建议
- 避免直接使用
!强制解包null值,建议添加null检查,防止空指针异常:
void getLocation() async { Locator loca = Locator(); await loca.getCurrentLocation(); if (loca.latitude != null && loca.longitude != null) { latitood = loca.latitude!; longitood = loca.longitude!; getData(); } else { print('无法获取位置信息'); // 可添加提示用户开启定位权限的逻辑 } }
内容的提问来源于stack exchange,提问作者Sagar Jadhav
相关产品推荐
相关产品推荐

