DEV Community

Cover image for Flutter GetX Example – Category Selection
Bart van Wezel
Bart van Wezel

Posted on • Originally published at bartvwezel.nl on

Flutter GetX Example – Category Selection

In the latest blog posts, I wrote about Flutter Hooks, Provider, and Riverpod to simplify state management in Flutter. We described how to streamline an interactive category selection application. The user can select categories in one Widget and access those categories in another Widget. With the state management solutions, this is a lot easier to reason about, write and maintain the code. There are multiple solutions, such as GetX and Riverpod, which have different approaches. In this blog post, we will explain how to create an example Flutter application with GetX.

Add GetX to your Flutter Project

Before we can start with coding, we are going to add the GetX dependency to the project first.

dependencies:
  flutter:
    sdk: flutter
  get: ^4.1.4
Enter fullscreen mode Exit fullscreen mode

Do not forget to install the dependency, running the following command:

flutter pub get
Enter fullscreen mode Exit fullscreen mode

That is it! We can now start with the example. The example we are going to build is a list of selectable categories. Underneath the checkboxes is a list that displays the currently selected values. This means that two Widgets need access to the list of categories and the currently selected values.

Before we look at the GetX state management, I will first explain the data we will display. The category has a name and a color. For this, we use a simple CategoryWidget such that we display the category the same everywhere.

class Category {
  final String name;
  final Color color;

  Category(this.name, this.color);
}

class CategoryWidget extends StatelessWidget {
  final Category category;

  const CategoryWidget({Key? key, required this.category}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Text(
      category.name,
      style: TextStyle(color: category.color),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Creating a GetxController

Now we will create a controller that manages the categories that are available for selection. The controller also manages the currently selected categories. For this, we can use a simple map from

class Controller extends GetxController {
  var _categories = {
    Category("Apple", Colors.red): false,
    Category("Orange", Colors.orange): false,
    Category("Banana", Colors.yellow): false,
  };

  void toggle(Category item) {
    _categories[item] = !(_categories[item] ?? true);
    update();
  }

  get selectedCategories =>
      _categories.entries.where((e) => e.value).map((e) => e.key).toList();

  get categories => _categories.entries.map((e) => e.key).toList();
}
Enter fullscreen mode Exit fullscreen mode

With GetX we can make the categories an observable. This means that we do not have to trigger updates on changes on the current value.

class Controller extends GetxController {
  var _categories = {
    Category("Apple", Colors.red): false,
    Category("Orange", Colors.orange): false,
    Category("Banana", Colors.yellow): false,
  }.obs;

  void toggle(Category item) {
    _categories[item] = !(_categories[item] ?? true);
  }

  get selectedCategories =>
      _categories.entries.where((e) => e.value).map((e) => e.key).toList();

  get categories => _categories.entries.map((e) => e.key).toList();
}
Enter fullscreen mode Exit fullscreen mode

Using the GetXController

Let’s take a look at how to access this controller. We can use the helper function Get.put into creating the Controller for us. With the controller, we can access the public function we created at the controller.

class CategoryFilter extends StatelessWidget {
  final controller = Get.put(Controller());

  @override
  Widget build(BuildContext context) {
    return Flexible(
      child: Obx(
        () => ListView.builder(
          itemCount: controller.categories.length,
          itemBuilder: (BuildContext context, int index) {
            return CheckboxListTile(
              value: controller.selectedCategories
                  .contains(controller.categories[index]),
              onChanged: (bool? selected) =>
                  controller.toggle(controller.categories[index]),
              title: CategoryWidget(category: controller.categories[index]),
            );
          },
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

The controller is great, but we also want to access the controller in another Widget. This is possible with the helper function Get.find , GetX will find the Controller for us. When we found the controller, we can again access the controller to display the currently selected categories.

class SelectedCategories extends StatelessWidget {
  final Controller controller = Get.find();

  @override
  Widget build(BuildContext context) {
    return Flexible(
      child: Obx(
        () => ListView.builder(
          itemCount: controller.selectedCategories.length,
          itemBuilder: (BuildContext context, int index) {
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: CategoryWidget(
                category: controller.selectedCategories[index],
              ),
            );
          },
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

With GetX is really simple to extract your state away from the views. GetX is useful for state management and has useful utilities for route management, dependency injection, which we will discuss in the next blog posts. You can find the full code of this example here on Github. If you still have any questions, remarks, or suggestions, do not hesitate to leave a comment or send a message!

The post Flutter GetX Example – Category Selection appeared first on Barttje.

Latest comments (1)

Collapse
 
pablonax profile image
Pablo Discobar

Good job! If you are interested in this topic, you can also look at my article about free vs paid Flutter templates. I'm sure you'll find something useful there, too.  - dev.to/pablonax/free-vs-paid-flutt...