Flutter天气应用报错:在null对象上调用了'[]'方法
解决Flutter天气应用的NoSuchMethodError错误
错误信息
I/flutter (30216): NoSuchMethodError: The method '[]' was called on null. I/flutter (30216): Receiver: null I/flutter (30216): Tried calling: [](0)
问题定位
错误根源在locationToLatLng方法中:当OpenWeather地理编码API返回错误对象(如API密钥无效、请求参数错误)或空数组(未找到匹配地点)时,直接调用jsonDecode(response.body)[0]会触发问题:
- 若API返回错误对象(格式为
Map<String, dynamic>),调用[0]会返回null,将null传入GeocodeData.fromJson后,模型内部调用[]方法就会抛出上述错误。 - 若API返回空数组,调用
[0]会直接抛出RangeError。
修复方案
修改locationToLatLng方法,增加对返回数据的类型和非空校验:
Future<GeocodeData?> locationToLatLng(String location) async { try { Uri url = Uri.parse( 'http://api.openweathermap.org/geo/1.0/direct?q=$location&limit=5&appid=$apiKey', ); final http.Response response = await http.get(url); if (response.statusCode != 200) return null; final decodedData = jsonDecode(response.body); // 校验数据类型为List且非空 if (decodedData is! List || decodedData.isEmpty) { return null; } // 校验第一个元素为Map类型 final firstItem = decodedData[0]; if (firstItem is! Map<String, dynamic>) { return null; } return GeocodeData.fromJson(firstItem); } catch (e) { print(e); return null; } }
额外优化建议
处理
late变量初始化问题:代码中weather和additionalWeatherData使用late修饰,若未成功获取数据就访问这些变量,会抛出LateInitializationError。建议改为可空类型并添加空校验:Weather? weather; AdditionalWeatherData? additionalWeatherData;在UI层使用时,通过
weather?.xxx或空判断避免错误。增强API错误处理:在
getCurrentWeather和getDailyWeather中,除捕获异常外,还应检查API返回的错误码(如cod字段),例如:final extractedData = json.decode(response.body) as Map<String, dynamic>; if (extractedData['cod'] != 200) { throw Exception(extractedData['message'] ?? 'Failed to fetch weather'); } weather = Weather.fromJson(extractedData);
内容的提问来源于stack exchange,提问作者Stepan Volkov
相关产品推荐
相关产品推荐

