Flutter State Managment

What is Flutter Getx

Flutter State Managment

What is GetX?

GetX is not only a state management library, but instead, it is a microframework combined with route management and dependency injection. It aims to deliver top-of-the-line development experience in an extra lightweight but powerful solution for Flutter. GetX has three basic principles on which it is built:

  1. Performance: focused on minimum consumption of memory and resources
  2. Productivity: intuitive and efficient tool combined with simplicity and straightforward syntax that ultimately saves development time
  3. Organization: decoupling business logic from view and presentation logic cannot get better than this. You do not need context to navigate between routes, nor do you need stateful widgets

The three pillars of GetX

  1. State management: GetX has two state managers. One is a simple state manager used with the GetBuilder function, and the other is a reactive state manager used with Getx or Obx. We will be talking about it in detail below
  2. Route management: whether navigating between screens, showing SnackBars, popping dialog boxes, or adding bottom sheets without the use of context, GetX has you covered. I will not write details on route management because it is beyond the scope of this article, but indeed a few examples to get an idea of how GetX syntax simplicity works
  3. Dependency management: GetX has a simple yet powerful solution for dependency management using controllers. With just a single line of code, it can be accessed from the view without using an inherited widget or context. Typically, you would instantiate a class within a class, but with GetX, you are instantiating with the Get instance, which will be available throughout your application

Value-added features of GetX

GetX has some great features out of the box, making it even easier to develop mobile applications in Flutter without any boilerplate code:

  1. Internationalization: translations with key-value maps, various language support, using translations with singulars, plurals, and parameters. Changing the application’s locale using only the Get word throughout the app
  2. Validation: email and password validations are also covered by GetX. Now you do not need to install a separate validation package
  3. Storage: GetX also provides fast and extra light synchronous key-value memory backup of data entirely written in Dart that easily integrates with the GetX core package
  4. Themes: switching between light and dark themes is made simple with GetX
  5. Responsive view: if you are building an application for different screen sizes, you just need to extend with GetView, and you can quickly develop your UI, which will be responsive for desktop, tablet, phone, and watch

Let’s get going with GetX state management

I will do this step by step, which I always like to do, and I will try to be descriptive and explain the process in as much detail as possible.

Step 1: Create a new application

Create a brand new application in your preferred IDE. First, remove all the starter comments by selecting the find and replace option in the Edit menu and type this: \/\/.*. This will select Flutter’s comments in the starter code, and you can just hit the delete button.

Step 2: Add required dependencies

Add these dependencies in your pubspec.yaml file:

get: ^4.6.1           //YAML get_storage: ^2.0.3  //YAML

Run this command:

flutter pub get  //YAML

Before going on to Step 3, let me explain what we are doing here. I have created a small application that demonstrates the core functionalities of GetX. The application is about a store where the user can:

  1. change the name of the store
  2. add follower names
  3. add follower count
  4. change the status of the store from open to closed and vice versa
  5. add reviews to the store
  6. change the theme of the store from light to dark

All of the above will explain state management, dependency management, route management, storage, and themes.

We are more focused on state and dependency management here. The route, storage, and themes are just for the application’s aesthetics.

You can read along and test the application through this link.

Step 3: Update the MaterialApp Widget

After adding the dependencies, the first thing you need to do is change the MaterialApp widget to GetMaterialApp in your main.dart file. This gives access to all GetX properties across the application.

Step 4: Add GetX Controller

We have already established that GetX separates the UI from the business logic. This is where GetX Controller comes into play.

You can always create more than one controller in your application. The GetX Controller class controls the state of the UI when you wrap an individual widget with its Observer so that it only rebuilds when there is a change in the state of that particular widget.

We are adding a new Dart file to create our controller class, StoreController, which extends GetxController:

class StoreController extends GetxController {}

Next, we add a few variables and initialize them with default values.

Normally we would add these variables like this as given below:

final storeName = 'Thick Shake';

But, when using GetX, we have to make the variables observable by adding obs at the end of value. Then when the variable changes, other parts of the application that depend on it will be notified about it. So now, our initialized value will look like this:

final storeName = 'Thick Shake'.obs;

Step 5: Dependency injection

In layman’s terms, we add the controller class we just created into our view class. There are three ways to instantiate.

  1. Extending the whole view class with GetView and injecting our StoreController with it:class Home extends GetView<StoreController>{}
  2. Instantiating the storeController like this:final storeController = Get.put(StoreContoller())
  3. For option three, start by creating a new StoreBinding class and implementing Bindings. Inside its default dependencies, you need to lazyPut the StoreController by using Get.lazyPut(). Secondly, you need to add the binding class inside the initialBinding property in GetMaterialWidget.

Lastly, instead of Get.Put as mentioned above, now you can use Get.find and GetX will find your controller for you when you instantiate in any of your classes:

 

class StoreBinding implements Bindings { // default dependency @override void dependencies() {   Get.lazyPut(() => StoreController(); } }

 

@override Widget build(BuildContext context) { return GetMaterialApp(   debugShowCheckedModeBanner: false,   title: 'GetX Store',   initialBinding: StoreBinding(), }

 

class UpdateStoreName extends StatelessWidget { UpdateStoreName({Key? key}) : super(key: key); //Getx will find your controller. final storeController = Get.find<StoreController>();

 

Step 6: Instantiate Controller

Since we have extended our Home view with GetView and created a binding class to lazyPut our controller inside it, we will now use Get.find to instantiate our controller inside our classes.

First, we add a new stateless widget, UpdateStoreName. Instantiate our controller class like this:

final storeController = Get.find<StoreController>();

 

Other GetX features

Route management

Traditionally, when a user wants to go from one screen to another with a click of a button, code would look like this:

Navigator.push(context,    MaterialPageRoute(builder: (context)=> Home()));

 

But, with GetX, there are literally just two words:

Get.to(Home());

 

When you want to navigate back to your previous screen:

Navigator.pop(context);

There is absolutely no need for context when you are using GetX:

Get.back();

If you have a dialog or a drawer opened and you want to navigate to another screen while closing the drawer or dialog, there are two ways to do this with default Flutter navigation:

  1. Close the drawer or dialog and then navigate like this:Navigator.pop(context); Navigator.push(context,    MaterialPageRoute(builder: (context)=> SecondScreen()));
  2. If you have named routes generated:Navigator.popAndPushNamed(context, '/second');