Flutter / GetX Basics / STEP5: Model
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; Ad ad; } create constructor
class UserListModel { int page; int perPage; int total; int totalPages; List data; Ad ad; UserListModel( {this.page, this.perPage, this.total, this.totalPages, this.data, this.ad}); } convert json to object
UserListModel.fromJson(Map json) { page = json['page']; perPage = json['per_page']; total = json['total']; totalPages = json['total_pages']; if (json['data'] != null) { data = new List(); json['data'].forEach((v) { data.add(new Data.fromJson(v)); }); } ad = json['ad'] != null ? new Ad.fromJson(json['ad']) : null; } convert to json
Map toJson() { final Map data = new Map (); 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 json) { id = json['id']; email = json['email']; firstName = json['first_name']; lastName = json['last_name']; avatar = json['avatar']; } Map toJson() { final Map data = new Map (); 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
complete codeclass Ad { String company; String url; String text; Ad({this.company, this.url, this.text}); Ad.fromJson(Map json) { company = json['company']; url = json['url']; text = json['text']; } Map toJson() { final Map data = new Map (); data['company'] = this.company; data['url'] = this.url; data['text'] = this.text; return data; } } class UserListModel { int page; int perPage; int total; int totalPages; List data; Ad ad; UserListModel( {this.page, this.perPage, this.total, this.totalPages, this.data, this.ad}); UserListModel.fromJson(Map json) { page = json['page']; perPage = json['per_page']; total = json['total']; totalPages = json['total_pages']; if (json['data'] != null) { data = new List(); json['data'].forEach((v) { data.add(new Data.fromJson(v)); }); } ad = json['ad'] != null ? new Ad.fromJson(json['ad']) : null; } Map toJson() { final Map data = new Map (); 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 json) { id = json['id']; email = json['email']; firstName = json['first_name']; lastName = json['last_name']; avatar = json['avatar']; } Map toJson() { final Map data = new Map (); 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 json) { company = json['company']; url = json['url']; text = json['text']; } Map toJson() { final Map data = new Map (); 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().obs; call api
void onInit() { _apiGetUserList(); super.onInit(); } set api response to model
complete codeUserListModel userListModel = UserListModel.fromJson(json.decode(value.body)); userListData.value = userListModel.data; 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().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
complete codeListView.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); }), ), ), 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: [ 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); }), ), ), ), ), ], ), ), ); } }