How to Fetch List from Api in Flutter using Getx

In this blog, we will explore How to Fetch List from Api in Flutter using Getx with proper example step by step in 2024.
Let's start without wasting time How to get list from api in flutter using getx after read this blog you will be master of integrating any api in flutter using Getx.

How to Fetch List from Api in Flutter using Getx

How to Fetch List from Api in Flutter using Getx with example Step by Step in 2024

Step 1 : Add some important dependencies in your "pubspec.yaml" File - See Below Snippet.

dependencies:
flutter:
sdk: flutter

# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
http: ^1.2.1
get: ^4.6.6

-> Here we added two dependencies :
"http: ^1.2.1" -> For networking purpose use.
"get: ^4.6.6" -> for Getx purpose generally use for state management and getx pre defined utilities.  

Step 2 : Create "main.dart" File in your Lib folder.

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:my_test_app/screens/user_list_screen.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
textTheme: const TextTheme(
headlineLarge: TextStyle(
color: Colors.white, fontSize: 25, fontFamily: 'MainFont'),
headlineMedium: TextStyle(color: Colors.black, fontSize: 20),
titleMedium: TextStyle(color: Colors.red, fontSize: 16),
),
useMaterial3: true,
),
home: const UserListScreen(),
);
}
}

Imp Note:
-> Remember when your using Getx state management then you should replace "MaterialApp" to "GetMaterialApp" as above you can see in "build overrided method" i have used "GetMaterialApp" instead to "MaterialApp" so this is very important if you forgot to use this then you don't have to use Getx features it will getting issue on runtime.

-> Call "UserListScreen()" dart file on home section here that means once your application open then User List Screen directly appears in your app.

Step 3 : Create "api_end_points.dart" File in your Lib folder.

class ApiEndPoints {
static const String baseUrl = 'https://reqres.in/';
static var authEndpoints = _AuthEndPoints();
}

class _AuthEndPoints {
final String userListApi = 'api/users';
}

Step 4 : Create "user_list_model.dart" File in your Lib folder.

import 'dart:convert';

UserListModel userListModelFromJson(String str) =>
UserListModel.fromJson(json.decode(str));

String userListModelToJson(UserListModel data) => json.encode(data.toJson());

class UserListModel {
int? page;
int? perPage;
int? total;
int? totalPages;
List<Data>? data;
Support? support;

UserListModel(
{this.page,
this.perPage,
this.total,
this.totalPages,
this.data,
this.support});

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 = <Data>[];
json['data'].forEach((v) {
data!.add(Data.fromJson(v));
});
}
support =
json['support'] != null ? Support.fromJson(json['support']) : null;
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['page'] = page;
data['per_page'] = perPage;
data['total'] = total;
data['total_pages'] = totalPages;
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
if (support != null) {
data['support'] = support!.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 = <String, dynamic>{};
data['id'] = id;
data['email'] = email;
data['first_name'] = firstName;
data['last_name'] = lastName;
data['avatar'] = avatar;
return data;
}
}

class Support {
String? url;
String? text;

Support({this.url, this.text});

Support.fromJson(Map<String, dynamic> json) {
url = json['url'];
text = json['text'];
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['url'] = url;
data['text'] = text;
return data;
}
}

-> Create a Model class according to your Api response. Click below link where you can easily create your model class online. Basically you need to convert JSON to Dart file then you can use in your studio. Firstly copy your Api response then paste below link (website) and convert to Dart File. copy same Dart File and create same name file in your "lib" folder and finally paste that Dart File code in your newly created file.


Step 5 : Create "user_list_controller.dart" File in your Lib folder.

import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import '../model/user_list_model.dart';
import '../services/api_end_points.dart';
import 'package:flutter/material.dart';

class UserListController extends GetxController {
var userList = <Data>[].obs;
var isLoading = false.obs;

Future<void> userListApi() async {
isLoading.value = true;
try {
final queryParameters = {
'page': 1,
};

var url = Uri.parse(
"${ApiEndPoints.baseUrl}${ApiEndPoints.authEndpoints.userListApi
}?page=1&per_page=10");

var response = await http.get(url);
if (response.statusCode == 200) {
isLoading.value = false;
userList.value = userListModelFromJson(response.body).data!;
} else {
isLoading.value = false;
Get.snackbar(
'Error',
"User list api not responding",
snackPosition: SnackPosition.BOTTOM,
forwardAnimationCurve: Curves.elasticInOut,
reverseAnimationCurve: Curves.easeOut,
);
}
} catch (error) {
isLoading.value = false;
Get.snackbar(
'Exception - ',
error.toString(),
snackPosition: SnackPosition.BOTTOM,
forwardAnimationCurve: Curves.elasticInOut,
reverseAnimationCurve: Curves.easeOut,
);
}
}

@override
void onInit() {
userListApi();
super.onInit();
}
}

-> In the above controller class i have implemented Api calls and mange the Api responses. with the help of this class i have fetch response from server and pass same response to user list screen with help of Getx obs.

-> Finally i have call this Api method inside overrided method i.e. "onInit()". this method will only be called once when the stateful widget is initialized.

Step 6 : Create Final "user_list_screen.dart" File in your Lib folder (Complete Code).

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:my_test_app/controller/user_list_controller.dart';

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

@override
State<UserListScreen> createState() => _UserListScreenState();
}

class _UserListScreenState extends State<UserListScreen> {
var userListController = Get.put(UserListController());

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("User List Page"),
backgroundColor: Colors.lightBlueAccent,
),
body: Obx(() {
if (userListController.isLoading.value) {
return const Center(child: CircularProgressIndicator());
}
return ListView.builder(
itemCount: userListController.userList.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(10.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: Container(
color: Colors.indigo,
child: ListTile(
subtitleTextStyle: const TextStyle(color: Colors.white),
titleTextStyle: const TextStyle(color: Colors.white),
title: Text(
"${userListController.userList[index].firstName} "
"${userListController.userList[index].lastName}"),
subtitle:
Text(userListController.userList[index].email ?? ""),
),
),
),
);
});
}),
);
}
}

->In the above screen i have created design of user list and manage the Api response with the help of Getx Obx (Observer).

-> Call this screen on "main,dart" file you can check step 2.

Reference

Here are the reference blog of complete tutorial of How to Fetch List from Api in Flutter using Getx step by step in 2024 you can easily learn and use in your code and below i have attached video if you guys want to learn more then watch below video thank you for your support.



Conclusion

In this blog i have explain you How to Fetch List from Api in Flutter using Getx step by step in 2024. you can easily use this code and modify according to your need.

Final output of this code

How to Fetch List from Api in Flutter using Getx
Oversimplified Coding

I am Shubhangam Upadhyay founder of Oversimplified Coding. My motive of this blog to help those developer are just start there carrier in coding line. We cover here Android, Kotlin, Core Java, Jetpack Compose and Flutter etc. related topics. I have 6+ Years of experience in Android Development and working on MNC company as a Senior Android Developer Position. I have worked on 5 different companies and experience on many different type of real time application project.

*

Post a Comment (0)
Previous Post Next Post