GetX for your Flutter Applications Part 2: State Management

GetX for your Flutter Applications Part 2: State Management

A trident package to manage all states, routes and dependencies.

In the previous part, we went through the introduction for the GetX package and explored the usage of some GetX methods. Now, we are going to explore more on implementation of GetX State Management in Flutter. In GetX State Management, business logic is separated from views while dependencies can also be separated using bindings. You can refer the previous article here.

Introducing the Technologies

GetxController

GetxController is a class where our business logic is defined and all our variables and methods are declared to be used from the UI. Each controller class extending from GetxController offers a disposable interface which reduces the manual task of disposing the controller whenever a widget is removed from navigation stack. GetxController comes with lifecycle which replaces methods of StatefulWidgets.

Update(): Using this, widgets can listen to the changes made by the methods defined in controller. It is similar to notifyListeners in providers

onInit(): It is called immediately after the widget is allocated memory.

onReady(): It is called immediately after the widget is rendered on screen.

onClose(): It is called just before the controller is deleted from memory.

GetBuilder

GetBuilder is used to make UI Screens or views interact with the variables and methods on the controllers. From here, we can call functions and listen to the changes in states. GetBuilder is the best way for managing ephemeral state.

GetX

GetX is like GetBuilder, but with streams. Here, we can add .obs to any variable to make them observable.

Obx

This is used in case if we want to use multiple controllers .

Mixin

Mixin is used to combine GetBuilder and Obx

Implement GetX State Management through the Simple State Manager method:

GetX State management can be implemented in any one of four ways depending on the need. Here, we shall dive deep into the first way of implementing GetX with GetxController and GetBuilder for creating a To-do app to add a list of items. To see how its done, follow the steps given below:

GetX.gif

Step 1 : Firstly, install Get in your pubspec.yaml file and run flutter pub get to get the dependencies as shown below:

dependencies:
  get: ^3.26.0

Step 2: Next, create a TodoController class which extends to the GetxController and define the required methods and variables, as shown:

class TodoController extends GetxController {
 /** list of strings to be displayed on the list **/
  List<String> todoItems = [];  
  /** method to add todo list to the list view **/
  void addTodo() {
    int index = todoItems.length;
    todoItems.add('Item' + index.toString());
    /** Notify changes in method, variables to the views **/
    update(); 
  }
}

Step 3: In this short step, create the UI Screens.

Step 4: Declare GetBuilder on the screen where you will implement the to-do function for adding items on the list by initiating the TodoController(). This process is as follows:

return GetBuilder(
        init: TodoController(),
        builder: (todoController) {
          return Scaffold(
              appBar: AppBar(
                backgroundColor: ColorConstants.appBarColor,
                title: Text(
                  'Todo App List',
                  style: 
          TextStyle(color: ColorConstants.primaryColor),
                ),
              ),
              floatingActionButton: FloatingActionButton(
                onPressed: () {
                  todoController.addTodo();
                },
                backgroundColor: ColorConstants.appBarColor,
                child: Icon(Icons.add),
              ),
              body: ListView.builder(
                  itemCount: todoController.todoItems.length,
                  itemBuilder: (BuildContext context, int index) 
                  {
                    return TodoListTile(
                    todoTitle: todoController.todoItems[index]);
                  }));
        });

Step 5: This is how the final result of the app should look like:

todo.png

You can checkout the complete code for the app here.

Conclusion

GetX reduces memory consumption, resulting in high performance and an organized code. So, unless you need to use a Mixin similar to TicketProviderStateMixin, it will be unnecessary to create StatefulWidgets while using Getx as your State Management.

In the upcoming articles you will get an insight into the on the other techniques employed by Getx.

Thank you so much for reading!