Home > database >  NoSuchMethodError The method '[]' was called on null. Tried calling: []("forecastday&
NoSuchMethodError The method '[]' was called on null. Tried calling: []("forecastday&

Time:08-22

This is the code `

class WeatherModel {
  String date;
  double temp;
  double maxTemp;
  double minTemp;
  String weatherStateName;

  WeatherModel(
      {required this.date,
      required this.temp,
      required this.maxTemp,
      required this.minTemp,
      required this.weatherStateName});

  factory WeatherModel.fromJson(dynamic data) {
    var jsonData = data['forecast']['forecastday'][0]['day'];
    

    return WeatherModel(
        date: data['location']['localtime'];
        temp: jsonData['avgtemp_c'];
        maxTemp: jsonData['maxtemp_c'];
        minTemp: jsonData['mintemp_c'];
        weatherStateName: jsonData['condition']['text']);
  }

  @override
  String toString() {
    return 'tem = $temp minTemp = $minTemp date = $date';
  }
}

this image

1

2

this is an error message.

The method '[]' was called on null. Tried calling: .

CodePudding user response:

You are getting null data from var jsonData = data['forecast']['forecastday'][0]['day']; You can accept null data like including ? data['forecast']?['forecastday']?[0]?['day']; , not sure ?[0]? is needed

class WeatherModel {
  String? date;
  double? temp;
  double? maxTemp;
  double? minTemp;
  String? weatherStateName;

  WeatherModel(
      {required this.date,
      required this.temp,
      required this.maxTemp,
      required this.minTemp,
      required this.weatherStateName});

  factory WeatherModel.fromJson(dynamic data) {
    var jsonData = data['forecast']?['forecastday']?[0]?['day'];

    return WeatherModel(
        date: data?['location']['localtime'] ?? "",
        temp: double.tryParse("${jsonData['avgtemp_c']}"),
        maxTemp: double.tryParse("${jsonData['maxtemp_c']}"),
        minTemp: double.tryParse("${jsonData['mintemp_c']}"),
        weatherStateName: jsonData?['condition']?['text']);
  }

  @override
  String toString() {
    return 'tem = $temp minTemp = $minTemp date = $date';
  }
}

You can make filed nullable for safety

  • Related