You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter调用OpenWeatherMap API无法同时获取温度与图标报错

问题分析与解决方案

核心错误原因

OpenWeatherMap API返回的weather字段是数组类型(包含多个天气状况条目),而非单个对象。你在WeatherData.fromJson中直接使用json["weather"]["icon"],相当于用字符串"icon"作为数组的索引,而数组要求索引必须是整数类型,因此抛出type 'String' is not a subtype of type 'int' of 'index'异常。

同时,因为解析icon时的未处理异常,导致fromJson函数执行中断,即使temp的赋值代码在前面,整个WeatherData实例初始化失败,最终视图中温度值变为null。

修复代码

修正WeatherData模型的fromJson构造函数

将icon的解析代码改为从weather数组的第一个元素中获取:

class WeatherData {
  int? temp;
  String? icon;

  WeatherData({
    this.temp,
    this.icon
  });

  WeatherData.fromJson(dynamic json) {
    var tempInKelvin = json["main"]["temp"];
    temp = (tempInKelvin - 273.15).round();
    // 修复:weather是数组,取第一个元素的icon字段
    if (json["weather"] is List && json["weather"].isNotEmpty) {
      icon = json["weather"][0]["icon"];
    }
  }
}

可选:增强异常处理(避免单个字段解析失败影响整个模型)

可以给fromJson添加try-catch,防止某字段解析失败导致整个对象初始化失败:

WeatherData.fromJson(dynamic json) {
  try {
    var tempInKelvin = json["main"]["temp"];
    temp = (tempInKelvin - 273.15).round();
    if (json["weather"] is List && json["weather"].isNotEmpty) {
      icon = json["weather"][0]["icon"];
    }
  } catch (e) {
    print("解析WeatherData时出错: $e");
  }
}

验证修复

修复后,重新请求API,icon字段将正确获取天气图标代码,同时temp字段的赋值不会被异常中断,视图中的温度值也能正常显示。

内容的提问来源于stack exchange,提问作者user19717894

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 16:36:22