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

Flutter使用toInt()转换后仍报错:type 'int' is not a subtype of 'double'

问题根源

你遇到的崩溃不是因为temp.toInt()转int赋值给temperature的步骤,而是API返回的weatherData['main']['temp']并不总是double类型——当温度是整数时,接口可能返回int类型的值,这时候你直接把它赋值给double类型的temp变量,就会触发type 'int' is not a subtype of 'double'的类型转换错误。

解决办法

不要直接将接口返回值强转成double,先统一转成num类型(int和double都是num的子类),再处理成你需要的类型:

可以用简化写法直接转成int:

temperature = (weatherData['main']['temp'] as num).toInt();

也可以分步处理更清晰:

num tempNum = weatherData['main']['temp'];
double temp = tempNum.toDouble();
temperature = temp.toInt();

这样不管接口返回的是int还是double,都能安全转换成int类型赋值给temperature。

修改后的完整代码示例
class _LocationScreenState extends State<LocationScreen> {
  WeatherModel weather = WeatherModel();
  late int temperature;
  late String cityName;
  late String weatherIcon;
  late String weatherMessage;
  
  @override
  void initState() {
    super.initState();
    updateUI(widget.locationWeather);
  }

  void updateUI(dynamic weatherData) {
    setState(() {
      if (weatherData == null) {
        temperature = 0;
        weatherIcon = 'Error';
        weatherMessage = 'Unable to get weather data';
        cityName = '';
        return;
      }
      // 修改后的温度处理逻辑
      temperature = (weatherData['main']['temp'] as num).toInt();
      
      var condition = weatherData['weather'][0]['id'];
      weatherIcon = weather.getWeatherIcon(condition);
      weatherMessage = weather.getMessage(temperature);

      cityName = weatherData['name'];
    });
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 07:09:39