0

I am learning to use api and all data in my interface is showing as null

in this section to understand where the problem lies i change ! with ?

How can I check if there is a problem while pulling the data?

I deleted the irrelevant parts to shorten the code.

  WeatherApiClient client = WeatherApiClient();
  Hava? data;

  Future<void> getData()async{
    data = await client.getCurrentWeather("London");
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(  
        body: FutureBuilder(
          future: getData(),
          builder: (context, snapshot){
            if(snapshot.connectionState==ConnectionState.done){
              return Column(
                children: [
                  GuncelVeri(Icons.wb_sunny_rounded, "${data?.derece}", "${data?.sehir}"),
                  bilgiler("${data?.humidity}","${data?.feels_like}", "${data?.pressure}","${data?.description}"),],
              );

            }
            else if(snapshot.connectionState == ConnectionState.waiting){
              return Center(
                child: CircularProgressIndicator(),
              );
            }
            return Container();
          },
        )

      ),
    );
  }
}
import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:weatherapp/model.dart';

class WeatherApiClient{
  Future<Hava>? getCurrentWeather(String? location)async{
    var endpoint = Uri.parse(
      "https://api.openweathermap.org/data/2.5/weather?q=$location&appid=9b6ece44d1233c111b86cacb5e3617f1&units=metric&lang=tr"
    );
    var response = await http.get(endpoint);
    var body = jsonDecode(response.body);
    print(Hava.fromJson(body));
    return Hava.fromJson(body);
}
}
2
  • 1
    first try to print(body) to see wether the response is null or not Commented Jan 3, 2022 at 1:44
  • 1
    user exception handling methods like try catch Commented Jan 3, 2022 at 5:53

1 Answer 1

1

Your are getting Null because you are trying to access the Hava class which have not been initilized yet.

You are printing print(Hava.fromJson(body)); before return Hava.fromJson(body);

First you want to check if what responce is getting from the http call.

for that you can just print the http responce like this:-

print(responce.body)

Then you can see what's the responce is.

They you can do return Hava.fromJson(body);

The right way

Check the status code of the responce, if the responce is 200 the cast the json responce to the model class or show an error

Refer code

Future<Profileclass> fetchprofile() async {
  String tokenFetch = await getStringValuesSF();

  return await Dio()
      .get(urlprofiledio,
          options: Options(
            headers: {
              'Authorization': 'Bearer $tokenFetch',
            },
          ))
      .then((response) {
    if (response.statusCode == 200) {
      return Profileclass.fromJson(jsonDecode(response.toString()));
    } else {
      throw Exception('Failed to load profile');
    }
  });
}

Thank you

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. The problem is in my album class. I defined the variable type incorrectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.