ERROR:NoSuchMethodError:方法'toDouble'在null上调用。接收方:null尝试调用:toDouble()

问题描述 投票:0回答:1

我正在尝试制作fromJson函数来解析json文件。但是在运行测试时,我收到此错误消息。

错误:NoSuchMethodError:方法'toDouble'在null上调用。接收者:null尝试调用:toDouble()

我不确定这有什么问题。

我的代码

weather_model_app_test.dart

group('fromJson', () {
    test('should return a valid model', () async {
      final Map<String, dynamic> jsonMap =
          json.decode(fixture('weather_app.json'));
      //act
      final result = WeatherAppModel.fromJson(jsonMap);
      //assert
      expect(result, tWeatherAppModel);
    });
  });

weather_app_model.dart

factory WeatherAppModel.fromJson(Map<String, dynamic> json) {
    return WeatherAppModel(
      weatherMain: json['weather'][0]['main'],
      weatherDescription: json['weather'][0]['description'],
      temp: (json['main']['temp'] as double).toDouble(),
      minTemp: (json['main']['temp_min'] as double).toDouble(),
      maxTemp: (json['main']['temp_main'] as double).toDouble(),
      country: json['sys']['country'],
    );
  }

fixtures / weather_app.dart

{
  "coord": {
    "lon": 78,
    "lat": 20
  },
  "weather": [
    {
      "id": 500,
      "main": "Rain",
      "description": "light rain",
      "icon": "10d"
    }
  ],
  "base": "model",
  "main": {
    "temp": 301.51,
    "pressure": 1014,
    "humidity": 67,
    "temp_min": 301.51,
    "temp_max": 301.51,
    "sea_level": 1014,
    "grnd_level": 979
  },
  "wind": {
    "speed": 3.19,
    "deg": 77
  },
  "rain": {
    "3h": 1.81
  },
  "clouds": {
    "all": 45
  },
  "dt": 1572672029,
  "sys": {
    "country": "IN",
    "sunrise": 1572655775,
    "sunset": 1572696807
  },
  "timezone": 19800,
  "id": 1272596,
  "name": "Digras",
  "cod": 200
}
json flutter dart mockito tdd
1个回答
0
投票

不应该maxTemp: (json['main']['temp_main'] as double).toDouble(),

是weather_app_model.dart文件中的[temp_max]而不是[temp_main]

© www.soinside.com 2019 - 2024. All rights reserved.