Rest API Using GetX
Hello Everyone!! In this article, we learn about getx in Flutter. We cover many topics in this article. GetX is fast, and lightweight, and using this, we can easily manage states, and routing and can efficiently perform dependency injection.
If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.
Table Of Contents:
What is GetX?
There is many state management in flutter like Provider, GetX, Bloc, Riverpod, Mobx, etc. But GetX is not only a state management library, but instead, it is a micro-framework amalgamated with route management and dependency injection. It points to delivering a top-of-the-line development experience in an extra insubstantial but strong solution for Flutter.
Three Pillars of GetX:
there are three pillars of getx by which we can create our flutter application trouble-free. And it’s very easy to use in any flutter application.
1. State management
It has two different state management, Get-builder, and GetX/Obx. Get-builder is simple to state management and Obx is a reactive state manager.
> State Management:- State Management is the planned approach to manage all the interplay that a user performs on a flutter application and then return those changes to UI, update databases, server requests, etc.
> Reactive State Manager:- Reactive programming is as easy as state management. Reactive programming can estrange many people because it is said to be tangled. In this, we don’t need to create StreamControllers and StreamBuilder for each variable. We don’t use code generators.
This is your count variable:
var city= 'Agra';
To make it observable, you just need to add “.obs” to the end of it:
var city = 'Agra'.obs;
And in the UI, when you want to show that value and update the screen whenever the values changes, simply do this:
Obx(() => Text("${controller.city}"));
2. Route management
GetX Route Management concept is used to navigate from one screen to another and pass data between two screens, to close the snack bar, dialog, and bottom sheets in flutter programming. This makes the navigation much simpler than the welsh way of dealing with itinitialRoute: RouteConstant.homeScreen,
3. Dependency management
It is used to handle Multiple Repositories in Flutter. As a codebase begins to fatten, in an environment where you are developing multifold applications, it is usual to have some dependencies that are shared across projects.DataController dataController = Get.put(DataController());
Implementation:
First, We have to create a Flutter Application with the name rest_api_getx. and add the dependencies in pubspec.ymal file.
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
get: ^4.6.1
http: ^0.13.4
In the main. dart file we add Get before your MaterialApp, turning it into GetMaterialApp.
GetMaterialApp(
theme: ThemeData.dark(),
debugShowCheckedModeBanner: false,
getPages: getPages,
title: 'Rest API Using GetX Demo',
initialRoute: RouteConstant.homeScreen,
);
We add dark theme in theme and set debugShowCheckedModeBanner as false, pass the initalRoute which is homescreen() for using route_constant we have to add getPages.
And create binding file, home_binding.dart.
class HomeScreenBinding extends Bindings {
@override
void dependencies() {
Get.lazyPut<DataController>(
() => DataController(),
);
}
}
Also create a controller file, home controller. Create two-variable first for user_model and isDataLoading for loader
User_Model? user_model;
var isDataLoading = false.obs;
Fetch API in the controller.
getApi() async {
try{
isDataLoading(true);
http.Response response = await http.get(
Uri.tryParse('http://dummyapi.io/data/v1/user')!,
headers: {'app-id': '6218809df11d1d412af5bac4'}
);
if(response.statusCode == 200){
///data successfully
var result = jsonDecode(response.body);
user_model = User_Model.fromJson(result);
}else{
///error
}
}catch(e){
log('Error while getting data is $e');
print('Error while getting data is $e');
}finally{
isDataLoading(false);
}
}
Create getApi() in which Fetch API in the controller. we pass try, catch, and finally. In try first, we add isDataLoading loader as true. and create a response and add an API link by using HTTP. get. If the status code is true then it shows the data. otherwise, print the error. And In finally, we pass the isDataLoading loader as false.
Create a User_model file in which we add the model of API. we can easily create the data model by using JsonToDart. In this, we add our JSON file and convert it into a dart file.
class User_Model {
List<Data>? data;
int? total;
int? page;
int? limit;
User_Model({this.data, this.total, this.page, this.limit});
User_Model.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = <Data>[];
json['data'].forEach((v) {
data!.add(new Data.fromJson(v));
});
}
total = json['total'];
page = json['page'];
limit = json['limit'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
data['total'] = this.total;
data['page'] = this.page;
data['limit'] = this.limit;
return data;
}
}
class Data {
String? id;
String? title;
String? firstName;
String? lastName;
String? picture;
Data({this.id, this.title, this.firstName, this.lastName, this.picture});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
firstName = json['firstName'];
lastName = json['lastName'];
picture = json['picture'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['title'] = this.title;
data['firstName'] = this.firstName;
data['lastName'] = this.lastName;
data['picture'] = this.picture;
return data;
}
}
We already discussed route_management so we create a file with the name route_constant in which we add a string of routes.
class RouteConstant{
static const String homeScreen = '/home_screen';
}
and also create a get_pages_constant in which we use GetPage and add the name of route, page, and binding.
List<GetPage> getPages = [
GetPage(
name: RouteConstant.homeScreen,
page: () => HomeScreen(),
middlewares: [
// Add here
// AuthGuard(),
],
binding: HomeScreenBinding()),
];
For the UI part create a dart file, homeScreen.dart. and get the home controller in that file by which we can access the controller’s variables and methods.
DataController dataController = Get.put(DataController());
In buildcontext we return Scaffold and in the property of Scaffold, we use appbar.
appBar: AppBar(
title: const Text(
'Rest API Using GetX',
),
centerTitle: true,
),
In the body, we wrap all the code with Obx for state management and add a condition that if isDataLoader is true it shows data otherwise it shows CircularProgressIndicator().
Obx(() => dataController.isDataLoading.value
? const Center(child: CircularProgressIndicator())
: _builScreen()),
In _builScreen we return ListView.builder(), in item count pass user model length. And in the builder, we pass context and index and return Column(). In the children of the column, we add SizedBox and container. In Container, we pass the row and add image and column. add the column as a child of the container. In the children, we pass three texts, title, first name, and last name.
Widget _builScreen(){
return ListView.builder(
itemCount: dataController.user_model!.data!.length,
itemBuilder: (context, index) {
return Column(
children: [
const SizedBox(
height: 10,
),
Container(
margin: const EdgeInsets.only(left: 20, right: 20),
padding: const EdgeInsets.only(left: 20),
height: 80,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20)),
child: Row(
children: [
CircleAvatar(
radius: 35,
backgroundImage: NetworkImage(dataController
.user_model!.data![index].picture!),
),
const SizedBox(
width: 30,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
dataController.user_model!.data! [index].title!
.toUpperCase(),
style: const TextStyle(
color: Colors.black, fontSize: 18),
),
Text(
dataController
.user_model!.data![index].firstName!,
style: const TextStyle(
color: Colors.black, fontSize: 18)),
Text(
dataController
.user_model!.data![index].lastName!,
style: const TextStyle(
color: Colors.black, fontSize: 18)),
],
),
],
)),
const SizedBox(
height: 10,
)
],
);
});
}
When we run the application, we ought to get the screen’s output like the underneath screen video.
Conclusion:
In this article, we have been through How to call Rest API Using GetX along with how to implement it in a Flutter. By using we can perform many operations and create a Flutter application.
❤ ❤ Thanks for reading this article ❤❤
If I got something wrong? Let me know in the comments. I would love to improve.
Clap 👏 If this article helps you.
GitHub Link:
Find the source code of the Rest API Using GetX:
GitHub – flutter-devs/rest_api_getx
You can’t perform that action at this time. You signed in with another tab or window. You signed out in another tab or…github.com
Feel free to connect with us:
And read more articles from FlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.
We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.