Search code examples
jsonflutterapidartflutter-futurebuilder

Flutter How to show data in listview.builder inside future builder with provider


I am working on an app where i am getting json response from api. I want to store all the objects coming from api into a list and then i want to show that list in a listview builder wrapped with future builder.

Here is my model `// To parse this JSON data, do
//
//     final viewCategoryModel = viewCategoryModelFromJson(jsonString);

import 'dart:convert';

ViewCategoryModel viewCategoryModelFromJson(String str) =>
    ViewCategoryModel.fromJson(json.decode(str));

String viewCategoryModelToJson(ViewCategoryModel data) =>
    json.encode(data.toJson());

class ViewCategoryModel {
  ViewCategoryModel({
    this.status,
    this.data,
  });

  bool? status;
  List<Datum>? data;

  factory ViewCategoryModel.fromJson(Map<String, dynamic> json) =>
      ViewCategoryModel(
        status: json["status"],
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "status": status,
        "data": List<dynamic>.from(data!.map((x) => x.toJson())),
      };
}

class Datum {
  Datum({
    this.categoryName,
    this.categoryCode,
    this.categoryType,
  });

  String? categoryName;
  String? categoryCode;
  String? categoryType;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        categoryName: json["category_name"],
        categoryCode: json["category_code"],
        categoryType: json["category_type"],
      );

  Map<String, dynamic> toJson() => {
        "category_name": categoryName,
        "category_code": categoryCode,
        "category_type": categoryType,
      };
}

` here is json response fromapi

{"status":true,"data":[{"category_name":"new category","category_code":"50","category_type":"Clothing"},{"category_name":"new category","category_code":"51","category_type":"Clothing"},{"category_name":"new category","category_code":"52","category_type":"Clothing"},{"category_name":"new category","category_code":"53","category_type":"Clothing"}]}

Please help


Solution

  • Without the service class you've done 45% of work, I would suggest you go through this Fetch Data from Internet

    Meanwhile you could do this:

    As the widget name suggests FutureBuilder() it expects a future type of data

    ///Step one ->Service class
    
    class FetchService{
      ///fetch all flags
      Future<ViewCategoryModel> fetData() async{
    
        try{
          Response response = await get(
            Uri.parse('your url here'),
            headers: {'Accept': 'application/json'}
          );
          if(response .statusCode == 200 || response.statusCode == 201){
               final viewCategoryModel = viewCategoryModelFromJson(request.body);
              return viewCategoryModel;
          }else{
           final viewCategoryModel = viewCategoryModelFromJson(request.body);
              return viewCategoryModel;
          }
        }catch(e){
          print('Error occurred: $e');
          return Future.error(e);
        }
      }
    }
    
    

    Then getting the data into the FutureBuilder()

    ...
     ///initialize
      late Future<ViewCategoryModel> viewCategory;
    
      @override
      void initState() {
        viewCategory = FetchService().fetchData();
        super.initState();
      }
    
    ...
     FutureBuilder<ViewCategoryModel>(
                      future: viewCategory,
                      builder: (context, AsyncSnapshot<ViewCategoryModel> snapshot){
        if (snapshot.hasError) {
                          print("Error found ${snapshot.error}");
                          return CircularProgressIndicator();
                        }else if(snapshot.hasData){
                      
                         return SizedBox(
                              height: MediaQuery.of(context).size.height,
                              child:ListView(
                                snapshot.data!.data!.length,(index){
                               return ListTile(
                                    title: Text(
                                      snapshot.data!.data![index].category_name
                                          .toString(),
                                    ),
                                  ),
                         }
                              )
                            );
             }
          }