Can t able fetch data form json using class in flutter dart

0 votes

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);
}

Mar 14, 2023 in Android by Tejashwini
• 780 points
1,239 views

1 answer to this question.

0 votes

To fix the issue of null temperature data, you can:

  1. Verify that the JSON response matches the Current class properties.
  2. Check if the JSON response is not nested.
  3. Make sure the fromJson() method is working correctly.
  4. Add error handling to your API call and JSON parsing code.

Here's an updated code that includes error handling:

Future<Current> getWeatherData({required String location}) async {
  final response = await http.get(Uri.parse(
      'http://api.weatherstack.com/current?access_key=a80c4dfea39ef2093f3a0423200bed6a&query=$location'));

  if (response.statusCode == 200) {
    final bodyJson = jsonDecode(response.body) as Map<String, dynamic>;

    try {
      final data = Current.fromJson(bodyJson['current']);

      if (data.temperature != null) {
        return data;
      } else {
        throw Exception('Temperature data is missing');
      }
    } catch (e) {
      throw Exception('Error parsing JSON: $e');
    }
  } else {
    throw Exception('Failed to load weather data: ${response.statusCode}');
  }
}

This code checks for errors during API call and JSON parsing, and throws an exception if something goes wrong.

To know more, join our Flutter Training today.

answered Mar 18, 2023 by vinayak

Related Questions In Android

0 votes
1 answer

Passing Data to a Stateful Widget in Flutter

The recommended way of passing data to ...READ MORE

answered Mar 18, 2023 in Android by pooja
16,367 views
0 votes
0 answers

How do I turn a C# object into a JSON string in .NET?

I have classes like these: class MyDate { ...READ MORE

Sep 20, 2022 in Android by Edureka
• 13,620 points
422 views
0 votes
1 answer

Open Contact information in Contact List using Phone Number of Contact Android Studio

You must first obtain the contact's CONTACT ...READ MORE

answered Nov 7, 2022 in Android by Edureka
• 12,690 points
965 views
0 votes
1 answer

How to Deserialize a list of objects from json in flutter Ask Question?

To deserialize a list of objects from ...READ MORE

answered Mar 28, 2023 in Flutter by vishalini
2,145 views
0 votes
1 answer

Dart_LoadScriptFromKernel: The binary program does not contain 'main'.

Hi@akhtar, You need to add the main() function ...READ MORE

answered Jul 21, 2020 in Others by MD
• 95,460 points
3,442 views
0 votes
1 answer

How to install Dart in Windows system?

Hi@akhtar, Dart is the programming language used to code Flutter apps. ...READ MORE

answered Jul 21, 2020 in Others by MD
• 95,460 points
1,008 views
0 votes
1 answer

flutter run: No connected devices

Hi@akhtar, To prepare to run and test your ...READ MORE

answered Jul 21, 2020 in Others by MD
• 95,460 points
4,053 views
0 votes
1 answer

How to change package name in flutter?

Yes, you can change the package name ...READ MORE

answered Mar 1, 2023 in Android by vishalini
3,065 views
0 votes
1 answer

How to create number input field in Flutter?

Yes, Flutter has a built-in widget called ...READ MORE

answered Mar 1, 2023 in Android by vishalini
7,498 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP