I am trying to retrieve the temperature data from a weather API using a generated class in Dart, created with the JSON to Dart Extension. I have been able to retrieve the entire JSON response from the API, but when I try to access a single data using the class, it just prints null.
from requests import session
Future<Current> getweatherData({required String location}) async {
// Replace with your actual API endpoint
final _response = await http.get(Uri.parse(
/* API URL removed for security */));
print(_response.body); // Add this line to print the response from the API
final _bodyJson = jsonDecode(_response.body) as Map<String, dynamic>;
final _data = Current.fromJson(_bodyJson);
print(_data.temperature); //showing null --
return _data;
}
Generated code.
import 'package:json_annotation/json_annotation.dart';
part 'current.g.dart';
@JsonSerializable()
class Current {
  @JsonKey(name: 'observation_time')
  String? observationTime;
  int? temperature;
  @JsonKey(name: 'weather_code')
  int? weatherCode;
  @JsonKey(name: 'weather_icons')
  List<String>? weatherIcons;
  @JsonKey(name: 'weather_descriptions')
  List<String>? weatherDescriptions;
  @JsonKey(name: 'wind_speed')
  int? windSpeed;
  @JsonKey(name: 'wind_degree')
  int? windDegree;
  @JsonKey(name: 'wind_dir')
  String? windDir;
  int? pressure;
  int? precip;
  int? humidity;
  int? cloudcover;
  int? feelslike;
  @JsonKey(name: 'uv_index')
  int? uvIndex;
  int? visibility;
  @JsonKey(name: 'is_day')
  String? isDay;
  Current({
    this.observationTime,
    this.temperature,
    this.weatherCode,
    this.weatherIcons,
    this.weatherDescriptions,
    this.windSpeed,
    this.windDegree,
    this.windDir,
    this.pressure,
    this.precip,
    this.humidity,
    this.cloudcover,
    this.feelslike,
    this.uvIndex,
    this.visibility,
    this.isDay,
  });
  factory Current.fromJson(Map<String, dynamic> json) {
    return _$CurrentFromJson(json);
  }
  Map<String, dynamic> toJson() => _$CurrentToJson(this);
}