Flutter API Resulting In Null

Viewed 886

currently working on a flutter project with API. I'm quite new to flutter,

My Code: Results null. Being working on it for quite some time but couldn't find a solution. First, try on a flutter app therefore I'm quite new to this, would appreciate any solutions or tips/resources. All variables are resulting in null as you can see I tried printing them couldn't figure out why.

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart';

void main() => runApp(MyApp());

Future<Data> getData() async {
    final response = await get("https://covid-api.com/api/reports?date=2020-03-25&iso=TUR&region_name=Turkey");

    if(response.statusCode == 200) {
      return Data.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Not Working');
    }
  }


class Data {
  String date;
  int confirmed;
  int deaths;
  int recovered;
  int confirmedDiff;
  int deathsDiff;
  int recoveredDiff;
  int active;
  int activeDiff;
  double fatalityRate;

  Data({
    this.date,
    this.confirmed,
    this.deaths,
    this.recovered,
    this.confirmedDiff,
    this.deathsDiff,
    this.recoveredDiff,
    this.active,
    this.activeDiff,
    this.fatalityRate,
  });

  factory Data.fromJson(Map<String, dynamic> json) {
    return Data(
    confirmed: json['confirmed'],
    deaths: json['deaths'],
    recovered: json['recovered'],
    confirmedDiff: json['confirmed_diff'],
    deathsDiff: json['deaths_diff'],
    recoveredDiff: json['recovered_diff'],
    active: json['active'],
    activeDiff: json['active_diff'],
    fatalityRate: json['fatality_rate'],
    );
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['date'] = this.date;
    data['confirmed'] = this.confirmed;
    data['deaths'] = this.deaths;
    data['recovered'] = this.recovered;
    data['confirmed_diff'] = this.confirmedDiff;
    data['deaths_diff'] = this.deathsDiff;
    data['recovered_diff'] = this.recoveredDiff;
    data['active'] = this.active;
    data['active_diff'] = this.activeDiff;
    data['fatality_rate'] = this.fatalityRate;
    return data;
  }
}

class MyApp extends StatelessWidget {
  final Future<Data> data = getData();
  @override
  Widget build(BuildContext context) {
    return MaterialApp(

        theme: ThemeData(primaryColor: Colors.red),
        home: Scaffold(
            appBar: AppBar(title: Text('COVID-19 Turkey')),
            body: Center(
              child: FutureBuilder<Data>(
                future: data,
                builder: (context, snapshot) {
                  print(snapshot.data.deaths);
                  print('wtf');
                  print(snapshot.data.deathsDiff);
                  print(snapshot.data.recovered);
                  if(snapshot.hasData){
                    return Text(snapshot.data.confirmed.toString());

                  } else if (snapshot.hasError) {
                    return Text('Error');
                  }

                  return Center(child: CircularProgressIndicator(),);
                },
            ),)

        )
      );
  }
}
2 Answers

I think the following is the right way of using FutureBuilder:

FutureBuilder(
  future: getData(),
  builder: (context, snapshot) {
    if (!snapshot.hasData
        && snapshot.connectionState != ConnectionState.done) {
      return Center(child: CircularProgressIndicator());
    }
    if(snapshot.hasData) {
       return Text(snapshot.data.confirmed.toString());
    } else if (snapshot.hasError) {
       return Text('Error');
    } 
});

Hope it helps!

The problem is in your JSON parsing. On this line,

return Data.fromJson(jsonDecode(response.body));

I called your API and it is giving a Map in which there is a data field and then there is a list of objects in it.

Your getData function needs to be like this,

Future<Data> getData() async {
final response = await get("https://covid-api.com/api/reports?date=2020-03-25&iso=TUR&region_name=Turkey");

if(response.statusCode == 200) {

  var data = jsonDecode(response.body);

  var firstObj = (data['data'] as List<dynamic>).first;

  return Data.fromJson(firstObj);
} else {
  throw Exception('Not Working');
}
}

Hope this fixes it for you.

Related