Search code examples
flutterflutter-layoutdart-null-safety

NoSuchMethodError The method '[]' was called on null. Tried calling: []("forecastday")


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: .


Solution

  • 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