STEP5: Model

  • Steps

    1. define model

    models/userlist.cart

    define class

    
                         class UserListModel {
    
                         }
                        

    define variables

    
                         class UserListModel {
                              int page;
                              int perPage;
                              int total;
                              int totalPages;
                              List<Data> data;
                              Ad ad;
    
                         }
    
                         

    create constructor

    
                         class UserListModel {
                              int page;
                              int perPage;
                              int total;
                              int totalPages;
                              List<Data> data;
                              Ad ad;
    
                              UserListModel(
                                    {this.page,
                                      this.perPage,
                                      this.total,
                                      this.totalPages,
                                      this.data,
                                      this.ad});
    
                         }
    
                         

    convert json to object

    
                         UserListModel.fromJson(Map<String, dynamic> json) {
                            page = json['page'];
                            perPage = json['per_page'];
                            total = json['total'];
                            totalPages = json['total_pages'];
                            if (json['data'] != null) {
                              data = new List<Data>();
                              json['data'].forEach((v) {
                                data.add(new Data.fromJson(v));
                              });
                            }
                            ad = json['ad'] != null ? new Ad.fromJson(json['ad']) : null;
                          }
    
                        

    convert to json

    
                        Map<String, dynamic> toJson() {
                            final Map<String, dynamic> data = new Map<String, dynamic>();
                            data['page'] = this.page;
                            data['per_page'] = this.perPage;
                            data['total'] = this.total;
                            data['total_pages'] = this.totalPages;
                            if (this.data != null) {
                              data['data'] = this.data.map((v) => v.toJson()).toList();
                            }
                            if (this.ad != null) {
                              data['ad'] = this.ad.toJson();
                            }
                            return data;
                          }
                        }
    
                        

    define data model

    
                          
    class Data {
      int id;
      String email;
      String firstName;
      String lastName;
      String avatar;
    
      Data({this.id, this.email, this.firstName, this.lastName, this.avatar});
    
      Data.fromJson(Map<String, dynamic> json) {
        id = json['id'];
        email = json['email'];
        firstName = json['first_name'];
        lastName = json['last_name'];
        avatar = json['avatar'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['id'] = this.id;
        data['email'] = this.email;
        data['first_name'] = this.firstName;
        data['last_name'] = this.lastName;
        data['avatar'] = this.avatar;
        return data;
      }
    }
    
    

    define ad model

    
      
    class Ad {
      String company;
      String url;
      String text;
    
      Ad({this.company, this.url, this.text});
    
      Ad.fromJson(Map<String, dynamic> json) {
        company = json['company'];
        url = json['url'];
        text = json['text'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['company'] = this.company;
        data['url'] = this.url;
        data['text'] = this.text;
        return data;
      }
    }
    
    
    complete code
    
    class UserListModel {
      int page;
      int perPage;
      int total;
      int totalPages;
      List<Data> data;
      Ad ad;
    
      UserListModel(
          {this.page,
            this.perPage,
            this.total,
            this.totalPages,
            this.data,
            this.ad});
    
      UserListModel.fromJson(Map<String, dynamic> json) {
        page = json['page'];
        perPage = json['per_page'];
        total = json['total'];
        totalPages = json['total_pages'];
        if (json['data'] != null) {
          data = new List<Data>();
          json['data'].forEach((v) {
            data.add(new Data.fromJson(v));
          });
        }
        ad = json['ad'] != null ? new Ad.fromJson(json['ad']) : null;
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['page'] = this.page;
        data['per_page'] = this.perPage;
        data['total'] = this.total;
        data['total_pages'] = this.totalPages;
        if (this.data != null) {
          data['data'] = this.data.map((v) => v.toJson()).toList();
        }
        if (this.ad != null) {
          data['ad'] = this.ad.toJson();
        }
        return data;
      }
    }
    
    class Data {
      int id;
      String email;
      String firstName;
      String lastName;
      String avatar;
    
      Data({this.id, this.email, this.firstName, this.lastName, this.avatar});
    
      Data.fromJson(Map<String, dynamic> json) {
        id = json['id'];
        email = json['email'];
        firstName = json['first_name'];
        lastName = json['last_name'];
        avatar = json['avatar'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['id'] = this.id;
        data['email'] = this.email;
        data['first_name'] = this.firstName;
        data['last_name'] = this.lastName;
        data['avatar'] = this.avatar;
        return data;
      }
    }
    
    class Ad {
      String company;
      String url;
      String text;
    
      Ad({this.company, this.url, this.text});
    
      Ad.fromJson(Map<String, dynamic> json) {
        company = json['company'];
        url = json['url'];
        text = json['text'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['company'] = this.company;
        data['url'] = this.url;
        data['text'] = this.text;
        return data;
      }
    }
    
    

    model usage

    home_controller.dart

    
    import 'package:flutter_api_calling_using_getx/models/userList.dart';
    class HomeController extends GetxController {
    
    }
    

    define variable for view

    
    var userListData = List<Data>().obs;
    

    call api

    
    void onInit() {
        _apiGetUserList();
        super.onInit();
      }
    
    

    set api response to model

    
    UserListModel userListModel =
          UserListModel.fromJson(json.decode(value.body));
          userListData.value = userListModel.data;
    
    complete code
    
    import 'dart:convert';
    import 'package:flutter/material.dart';
    import 'package:flutter_api_calling_using_getx/apis/request.dart';
    import 'package:flutter_api_calling_using_getx/models/userList.dart';
    import 'package:flutter_api_calling_using_getx/util/constants.dart';
    import 'package:get/get.dart';
    
    class HomeController extends GetxController {
      var userListData = List<Data>().obs;
      @override
      void onInit() {
        _apiGetUserList();
        super.onInit();
      }
    
      void _apiGetUserList() async {
        Future.delayed(
            Duration.zero,
                () => Get.dialog(Center(child: CircularProgressIndicator()),
                barrierDismissible: false));
    
        Request request = Request(url: urlUserList, body: null);
        request.get().then((value) {
          UserListModel userListModel =
          UserListModel.fromJson(json.decode(value.body));
          userListData.value = userListModel.data;
          Get.back();
        }).catchError((onError) {
          print(onError);
        });
      }
    
      void deleteItem(int index) {
        userListData.removeAt(index);
      }
    }
    
    

    Screen

    use userListData variable in screen

    In home_screen.dart

    
    final HomeController _homeController = Get.put(HomeController());
    

    listView with data from api

    
    ListView.builder(
                      itemCount: _homeController.userListData.length,
                      itemBuilder: (context, index) => ListTile(
                        title: Text(
                          _homeController.userListData[index].firstName,
                        ),
                        subtitle: Text(
                          _homeController.userListData[index].email,
                        ),
                        trailing: Image.network(
                          _homeController.userListData[index].avatar,
                          width: 80,
                          height: 80,
                          fit: BoxFit.contain,
                        ),
                        leading: IconButton(
                            icon: Icon(
                              Icons.delete,
                              color: Colors.black,
                            ),
                            onPressed: () {
                              _homeController.deleteItem(index);
                            }),
                      ),
                    ),
                  
    complete code
    
                  import 'package:flutter/material.dart';
    import 'package:flutter_api_calling_using_getx/core/controllers/home_controller.dart';
    import 'package:flutter_api_calling_using_getx/core/controllers/login_controllers.dart';
    import 'package:get/get.dart';
    import 'package:google_fonts/google_fonts.dart';
    
    class HomeScreen extends StatelessWidget {
    
    
      static String routeName = "/home_screen";
    
      final LoginController _loginController = Get.find();
      final HomeController _homeController = Get.put(HomeController());
    
      @override
      Widget build(BuildContext context) {
        print(_loginController.emailTextController.text);
        return Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            title: Text(
              'Dashboard',
            ),
          ),
          body: Container(
            padding: EdgeInsets.all(16),
            child: Column(
              children: <Widget>[
                Text(
                  'Welcome ${_loginController.emailTextController.text}',
                  style: GoogleFonts.exo2(
                    fontSize: 16,
                    color: Colors.black,
                    fontWeight: FontWeight.normal,
                  ),
                ),
                SizedBox(
                  height: 16,
                ),
                Expanded(
                  child: Obx(
                        () => ListView.builder(
                      itemCount: _homeController.userListData.length,
                      itemBuilder: (context, index) => ListTile(
                        title: Text(
                          _homeController.userListData[index].firstName,
                        ),
                        subtitle: Text(
                          _homeController.userListData[index].email,
                        ),
                        trailing: Image.network(
                          _homeController.userListData[index].avatar,
                          width: 80,
                          height: 80,
                          fit: BoxFit.contain,
                        ),
                        leading: IconButton(
                            icon: Icon(
                              Icons.delete,
                              color: Colors.black,
                            ),
                            onPressed: () {
                              _homeController.deleteItem(index);
                            }),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      }
    }