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.
Future<Current> getweatherData({required String location}) async {
final _response = await http.get(Uri.parse(
'http://api.weatherstack.com/current?access_key=a80c4dfea39ef2093f3a0423200bed6a&query=$location'));
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);
}