GetX State Management In Flutter

Learn How To Implement GetX State Management In Your Flutter Apps

Shubham Pandey
FlutterFly
8 min readMay 22, 2023

--

Whenever we start building any application in a flutter, we must decide which state management we need to use. It would be easier for you to make this decision with this blog. Here, in this tutorial: Flutter state management using GetX, I would like to explain GetX, a powerful flutter framework.

What is GetX?

GetX is a quick, stable, and light state management library in a flutter. There are so many State Management libraries in flutter like MobX, BLoC, Redux, Provider, and so forth.

GetX is additionally a strong miniature framework and utilizing this, we can oversee states, make routing, and can perform dependency injection.
State management permits you information transfer inside the application. What’s more, at whatever point information is passed, the application’s state is updated, thusly rebuilding the system.

Along these lines, developers must be especially cautious about managing the state of an application since state updation may at times appear to be exorbitant for a complex application.

Why GetX?

So, let’s dive a little deeper into why we need GetX to manage the state in the flutter app.

GetX is a very lightweight and powerful state management solution for flutter.

  • > High performance: GetX utilizes as less assets as could be expected. It doesn’t rely upon Streams or ChangeNotifier. All things being equal, it utilizes low inertness GetValue and GetStream to further develop execution.
  • > Less code: You might be tired of implementing boilerplate in the bloc pattern and wasting development energy on superfluous codes. Time is money, isn’t that so? In GetX, you won’t compose any boilerplate. You can accomplish the same thing a lot quicker, with less code in GetX. Don’t bother making classes for the state and event, since these boilerplates don’t exist in GetX.
  • > No code generation: There is a compelling reason need to utilize code generators by any means. So your significant development time won’t squander more on running code generators(build_runner) whenever you change your code.
  • > Don’t worry about context: Your application context is important. Yet, sending the context from your view to the controller can be, here and there lumbering. In GetX, you don’t have to do this. You can get to controllers inside one more controller with no unique context.
  • > No unnecessary rebuilds: Undesirable modifies are an issue of state managers based on ChangeNotifier. Whenever you roll out an improvement in your ChangeNotifier class, all widgets that rely upon that ChangeNotifier class are rebuilt. Some rebuilds might be superfluous and expensive. It might diminish the application’s performance too. You don’t need to stress over this in GetX since it doesn’t utilize the ChangeNotifier by any means.
  • > Code organization is simple: Bloc’s popularity comes from its prevalent code sorting-out capacities. It makes it more straightforward to isolate your business rationale from the show layer. GetX is a characteristic development for this as true documentation says. In GetX, you can isolate the business rationale as well as the show layer.

Principles:

There are three principles of GetX:

  • > Performance: When contrasted with other state management libraries, GetX is best since it consumes the least assets and gives better execution. It doesn’t utilize ChangeNotifier or Streams. Take a gander at the beneath RAM graph portraying different state managers.
  • > Productivity: GetX’s syntax is simple so it is useful. It saves a ton of time for the developers and speeds up the application since it doesn’t utilize additional assets. It utilizes just those assets which are right now required and after its work is done, the assets will be free naturally. If every one of the assets is stacked into the memory, it won’t be simply useful. So better to involve GetX in this.
  • > Organization: GetX code is coordinated as View, Logic, route, and dependency injection. So we needn’t bother with any additional context to navigate different screens. We can navigate to the screen without utilizing the unique circumstance so we are not dependent on the widget tree.

Three Pillars Of GetX:

  • > State Management: There are two types of state management:-

Simple State Manager: It uses the GetBuilder function.

Reactive State Manager: It uses GetX and Obx.

  • > Route Management: To make Widgets like Snackbar, Bottomsheets, dialogs, and so forth. Then, at that point, we can involve GetX in it because GetX can assemble these widgets without utilizing context.
  • > Dependency Management: GetX has a straightforward yet strong answer for dependency management utilizing controllers. To bring data from different Classes then with the assistance of GetX, we can do this in a solitary line of code. Eg: Get.put()
  • *Enough of the theory part. Let’s move forward in our Flutter state. management using GetX tutorial and implement it in our application.**

Install GetX

flutter pub add get

Run the above command in Android studio/vs code’s terminal, and it will add the latest GetX plugin to pubspec.yaml.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called main.dart inside the lib folder.

In the main. dart file, we will return GetMaterialApp(). Also, we will add a theme for color, and a home for showing starting screen.

Main Page

Create a new dart file called controller.dart inside the lib folder.

We will create a class called Controller inside it and extend the GetxController class. We will add the final count is equal to 0. obs. In GetX, to make a variable observable — this means that when it changes, other parts of our application depending on it will be notified. To do this we simply need to add .obs to the variable initialization. So for our above count variable, we will add .obs to 0.

To wrap things up with the Controller we will implement the increment method.

controller.dart

Create a new dart file called my_home_page.dart inside the lib folder.

First, we will create inside the MyHomePage class, we will instantiate the Controller.

final controller = Get.put(Controller());

For our count, we want the Text widget to be updated with the current count. So we will wrap the Text widget with Obx widget.

Obx(() => Text(
'clicks: ${controller.count}',
)),

We will add floatingActionButton, we will call the increment method when the floatingActionButton is pressed.

floatingActionButton: FloatingActionButton(
onPressed: controller.increment,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);

When we run the application, we ought to get the screen’s output like the underneath screen capture.

App

> Navigation In GetX:

On the home page, we will create a button ‘Go to next screen’ text and icon. On this button, onPressed method. We will add Get.to(() => const NextPage()) for navigating screen without using context.

ElevatedButton(
child: const Text('Navigate to Next Page'),
onPressed: () {
Get.to(() => NextPage());
},
),

When we run the application, we ought to get the screen’s output like the underneath screen capture.

My Home Page

Create a new dart file called next_page.dart inside the lib folder.

We will create a new NextPage class. In this class, we will add a text and an ElevatedButton and wrap into it a Column widget.

class NextPage extends StatelessWidget {
@override
Widget build(context){
return Scaffold(
appBar: AppBar(
title: const Text("Next Page"),
),
body: Center(child:
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'This is second page',
),

ElevatedButton(
child: const Text('Back to Page'),
onPressed: () {
Get.back();
},
),
],
)));
}
}

When the user presses the ‘Back to Page’ button then, the user back to the home screen. On this onPressed method, we will add Get. back() for navigation without using context.

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Next Page

> Snackbar:

On the home page, we will also create a show snackbar button using Getx in a flutter. In this button, onPressed method we will add inside Get. snackbar(). Also, we will add snackPosition and backgroundColor. In the child method, we will add the text ‘Show Snackbar’.

ElevatedButton(
onPressed: () {
Get.snackbar('GetX Snackbar', 'Yay! Awesome GetX Snackbar',
snackPosition: SnackPosition.BOTTOM,
backgroundColor: Colors.tealAccent);
},
child: const Text('Show Snackbar')),

> Dialog:

On the home page, we will also create a show alertDialog button using Getx in a flutter. In this button, onPressed method we will add inside Get. defaultDialog(). Also, we will add the title, middle text, textConfirm, confirmTextColor, and textCancel. In the child method, we will add the text ‘Show AlertDialog’.

ElevatedButton(
onPressed: () {
Get.defaultDialog(
title: 'GetX Alert',
middleText: 'Simple GetX alert',
textConfirm: 'Okay',
confirmTextColor: Colors.white,
textCancel: 'Cancel');
},
child: const Text('Show AlertDialog')),

> Bottom Sheet:

On the home page, we will also create a show bottom sheet button using Getx in a flutter. In this button, onPressed method we will add inside Get. bottomSheet(). For Bottom Sheet you write some code like this:

ElevatedButton(
onPressed: () {
Get.bottomSheet(
Wrap(
children: [
ListTile(
leading: Icon(Icons.wb_sunny_outlined),
title: Text("Light theme"),
onTap: () => {Get.changeTheme(ThemeData.light())},
),
ListTile(
leading: Icon(Icons.wb_sunny),
title: Text("Dark theme"),
onTap: () => {Get.changeTheme(ThemeData.dark())},
)
],
),
backgroundColor: Colors.green
);
},
child: const Text('Show BottomSheet')),

Conclusion:

In the article, I have explained the basic structure of GetX State Management in a flutter; you can modify this code according to your choice. This was a small introduction to GetX State Management On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying up the GetX State Management in your flutter projects. We will show you what GetX is?. Show the principles, and why GetX, etc of GetX State Management. Make a demo program for working with GetX. So please try it.

❤ ❤ 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 Flutter GetX State Management Demo:

This GitHub link helps you for the API implement also, I am adding some extra code for understanding to you how to manage API integration with GetX State Management. In this Code, You find Login Page, SignUp Page, Forgot Password and Some Demo API Integration for Listing the Movies and Details of Movies etc.

--

--