Flutter GetX Example – Category Selection
Tags: flutter, getx
Published: 2021-06-13 14:10:43

---
title: Flutter GetX Example – Category Selection
published: true
date: 2021-06-12 18:54:47 UTC
tags: Flutter,GetX
canonical_url: https://bartvwezel.nl/flutter/flutter-getx-example-category-selection/
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/odt2gyv3aioiifikwvlz.jpg
---

In the latest blog posts, I wrote about [Flutter Hooks](https://bartvwezel.nl/flutter/flutter-hooks-usestate-example/), [Provider](https://bartvwezel.nl/flutter/flutter-provider-example-category-selector/), and [Riverpod](https://bartvwezel.nl/flutter/riverpod-state-management-example-tic-tac-toe/) 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](https://pub.dev/packages/get) dependency to the project first.

```YAML
dependencies:
  flutter:
    sdk: flutter
  get: ^4.1.4
```

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

```shell
flutter pub get
```

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.

```dart
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),
    );
  }
}
```

## 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

```dart
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();
}
```

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.

```dart
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();
}
```

## 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.

```dart
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]),
            );
          },
        ),
      ),
    );
  }
}
```

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.

```dart
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],
              ),
            );
          },
        ),
      ),
    );
  }
}
```

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](https://github.com/Barttje/getx-category-selection-example). 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](https://bartvwezel.nl/flutter/flutter-getx-example-category-selection/) appeared first on [Barttje](https://bartvwezel.nl).