Home > Net >  Listing Data from API with Flutter
Listing Data from API with Flutter

Time:07-25

I can pull my data but not mirror it. The examples on the internet have always been used to reflect a single data. The data I have is multiple data. I want to reflect the data of different countries as a list. I used Listview.builder and ListTile but it didn't work. I keep getting different errors. I couldn't find an up-to-date and working example. Could you help?

I have an API. API URL: https://covid19-mohfw.herokuapp.com/

I converted this data as a model.

My Model:

class CovidModel {
  List<States>? states;
  Totals? totals;

  CovidModel({this.states, this.totals});

  CovidModel.fromJson(Map<String, dynamic> json) {
    if (json['states'] != null) {
      states = <States>[];
      json['states'].forEach((v) {
        states!.add(new States.fromJson(v));
      });
    }
    totals =
        json['totals'] != null ? new Totals.fromJson(json['totals']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.states != null) {
      data['states'] = this.states!.map((v) => v.toJson()).toList();
    }
    if (this.totals != null) {
      data['totals'] = this.totals!.toJson();
    }
    return data;
  }
}

class States {
  String? state;
  int? cases;
  int? recoveries;
  int? deaths;
  int? total;

  States({this.state, this.cases, this.recoveries, this.deaths, this.total});

  States.fromJson(Map<String, dynamic> json) {
    state = json['state'];
    cases = json['cases'];
    recoveries = json['recoveries'];
    deaths = json['deaths'];
    total = json['total'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['state'] = this.state;
    data['cases'] = this.cases;
    data['recoveries'] = this.recoveries;
    data['deaths'] = this.deaths;
    data['total'] = this.total;
    return data;
  }
}

class Totals {
  int? cases;
  int? recoveries;
  int? deaths;
  int? total;

  Totals({this.cases, this.recoveries, this.deaths, this.total});

  Totals.fromJson(Map<String, dynamic> json) {
    cases = json['cases'];
    recoveries = json['recoveries'];
    deaths = json['deaths'];
    total = json['total'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['cases'] = this.cases;
    data['recoveries'] = this.recoveries;
    data['deaths'] = this.deaths;
    data['total'] = this.total;
    return data;
  }
}

and my fetchCountry file from which I Pulled Data

import 'dart:convert';
import 'package:covidapp/models/covidModel.dart';
import 'package:http/http.dart' as http;

class FetchCountry {
  Future<CovidModel> fetchData() async {
    final response =
        await http.get(Uri.parse("https://covid19-mohfw.herokuapp.com/"));
    if (response.statusCode == 200) {
      final result = CovidModel.fromJson(jsonDecode(response.body));
      return result;
    } else {
      throw Exception('Error');
    }
  }
}

Finally, the part where I try to reflect the data:

import 'package:covidapp/models/covidModel.dart';
import 'package:flutter/material.dart';
import 'package:covidapp/services/fetchCountry.dart';

class covidPage extends StatefulWidget {
  const covidPage({Key? key}) : super(key: key);

  @override
  State<covidPage> createState() => _covidPageState();
}

class _covidPageState extends State<covidPage> {
  late Future<CovidModel> futureCountry = FetchCountry().fetchData();
  @override
  void initState() {
    super.initState();
    futureCountry = FetchCountry().fetchData();
  }

  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: Container(
        width: double.infinity,
        height: double.infinity,
        color: Color.fromRGBO(255, 246, 234, 1),
        child: Column(children: [
          SizedBox(
            height: MediaQuery.of(context).size.height * 0.03,
          ),
          const Text(
            'Covid Data',
            textAlign: TextAlign.center,
            style: TextStyle(
                fontSize: 29,
                fontWeight: FontWeight.w700,
                color: Color.fromARGB(255, 112, 108, 112)),
          ),
        ]),
      )),
    );
  }
}

CodePudding user response:

Store all your data in model instead of future model will work

 class _covidPageState extends State<covidPage> {
   late CovidModel? futureCountry;
 
   @override
   void initState() {
     super.initState();
     WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
       futureCountry = await FetchCountry().fetchData();
       print(futureCountry?.states?.length); // You can access all data with futureCountry?.
       setState(() {});
     });
   }

/// your code

CodePudding user response:

You can use a FutureBuilder like this:

FutureBuilder(
                future: futureCountry,
                builder: (context, snap) {
                  if (snap.connectionState == ConnectionState.waiting) {
                    return CupertinoActivityIndicator();
                  }
                  if (snap.hasError) {
                    return Text("Error!");
                  }
                  final data =
                      snap.data as CovidModel;
                  return ListView.builder(
                   shrinkWrap: true,
                   padding: EdgeInsets.symmetric(vertical: 20),
                   physics: const AlwaysScrollableScrollPhysics(),
                   itemCount: data.states.length,
                   itemBuilder: (c, index) => CovidDetailWidget(data[index]),
          );

                },
              )
  • Related