Flutter GetX State Management Framework

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
June 10, 2023

Flutter GetX State Management Framework

Flutter GetX is a popular state management framework in Flutter development. It is a lightweight and powerful framework that provides a simpler and faster way to build and manage stateful applications. The framework comes with several modules, including state management, dependency injection, and route management to handle the common challenges Flutter developers face while building applications.

Setting up GetX in Flutter

To get started with GetX in Flutter, we first need to add the dependency in our `pubspec.yaml` file:
dependencies:
  flutter:
    sdk: flutter
  get: ^4.6.1}
After adding the dependency, we can run `flutter pub get` to download the necessary packages. Next, we need to import the GetX package in our Dart file:
import 'package:get/get.dart';}
Then, we can start using GetX with just a few lines of code.

State Management with GetX

GetX has a simple approach to state management using the `GetBuilder` widget. This widget rebuilds only the portion of the UI that needs to update when there is a change in the state. Let's look at an example where we have a counter that increments every time a button is pressed:
class CounterController extends GetxController {
  var counter = 0.obs;
  
  void incrementCounter() {
    counter.value += 1;
  }
}

class MyHomePage extends StatelessWidget {
  final CounterController _counterController = Get.put(CounterController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("GetX Counter"),
      ),
      body: Center(
        child: GetBuilder(
          builder: (controller) => Text(
            "Counter: ${controller.counter}",
            style: TextStyle(fontSize: 28),
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _counterController.incrementCounter(),
        child: Icon(Icons.add),
      ),
    );
  }
}
In this example, the `CounterController` is responsible for the counter's state, and we have used `GetBuilder` to update the text widget whenever there is a change in the count value. Notice that we have added the `obs` in the `counter` variable to turn it into an observable. This makes GetX track any changes in the `counter` variable and update the UI accordingly. Also, we have used `Get.put(CounterController())` to create an instance of `CounterController`, and this can be accessed anywhere in the application.

Dependency Injection with GetX

GetX makes it simple to use dependency injection (DI) by using the `Get.put()` method. This makes it easy to manage and organize the dependencies in the application. Let's take an example of adding a `Storage` class as a dependency in our `CounterController`:
class Storage {
  Future saveCounter(int count) async {
    // save the count in local storage
  }

  Future getCounter() async {
    // get the count from local storage
    return 0; // for example's sake
  }
}

class CounterController extends GetxController {
  final Storage _storage = Get.find();
  var counter = 0.obs;
  
  void incrementCounter() {
    counter.value += 1;
    _storage.saveCounter(counter.value);
  }
}
In this example, we have created a `Storage` class and marked it for DI by using `Get.put(Storage())`. We have also used `Get.find()` to access the `Storage` class instance anywhere in the application. This way, we can easily manage our dependencies and have them accessible to whichever class we wanted, and we can use them anywhere in our application.

Route Management with GetX

GetX provides an elegant way to manage routes in the Flutter app using the `Get.to()` method. This method allows navigating to different routes in the application while also allowing us to pass arguments to the next screen. Here is an example of using routes with GetX:
class FirstScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("First")),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Get.to(SecondScreen(), arguments: "Hello from First screen");
          },
          child: Text("Go to Second"),
        ),
      ),
    );
  }
}

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final String arguments = Get.arguments;
    return Scaffold(
      appBar: AppBar(
        title: Text("Second"),
      ),
      body: Center(
        child: Text(arguments, style: TextStyle(fontSize: 24)),
      ),
    );
  }
}
In this example, we have used `Get.to()` to navigate from `FirstScreen` to `SecondScreen`, and the argument "Hello from First screen" is passed to the `SecondScreen`. We can then access this argument in the `build` method of the `SecondScreen` using `Get.arguments`.

Conclusion

GetX is a powerful and concise state management tool that solves many of the issues that Flutter developers face when building applications. There is a lot to learn about other GetX modules and features, but with the basics covered in this tutorial, you can quickly begin using the framework in your Flutter apps.