...

/

The StateMixin Class

The StateMixin Class

Learn to manage a controller’s loading state with StateMixin.

Introduction to StateMixin

StateMixin, as the name suggests, lets us define the controller’s state. It’s a niche feature where we can declare any data type as the controller’s state and manage its status. The status can be a success, error, loading, loadingMore, or empty. This feature becomes instrumental when dealing with REST API calls in the controller.

Implementation

Create UserModel to serve as the state of the controller as follows:

Press + to interact
class UserModel {
final String name;
final int age;
UserModel({required this.name, required this.age});
}

Next, create the controller and mix it with StateMixin. We will use UserModel as StateMixin’s type to declare it as the controller’s state.

Press + to interact
class UserController extends GetxController with StateMixin<UserModel> {}

Now that we have a custom state attached to our controller, let’s write the function to fetch user data from the database.

Press + to interact
class UserController extends GetxController with StateMixin<UserModel> {
// Fetches user from the database and returns UserModel.
Future<UserModel> fetchUser() async {
// Get data from the database.
final http.Response response = await http.get(Uri.parse('https://users.database.com/user/1'));
// Decode json from the response body.
final data = jsonDecode(response.body);
// Create the UserModel instance.
final UserModel user = UserModel(name: data['name'], age: data['age']);
return user;
}
}

Let’s introduce the change method. We use the change method to change the state of the controller. Here’s how it works:

Press + to interact
Future<UserModel> fetchUser() async {
final http.Response response = await http.get(Uri.parse('https://users.database.com/user/1'));
final data = jsonDecode(response.body);
final UserModel user = UserModel(name: data['name'], age: data['age']);
// This changes everything!
change(user);
return user;
}

change takes a parameter called newState. The user model created from the fetched data is the controller’s new state. We can now use data from this new state to create widgets in the UI.

Things don’t end here, though. As fetching from the database is an asynchronous function, we should consider adding a loading state. We should also have an error state in case the API call fails. And, in case the user’s name is missing from the database, we should also implement an empty state.

StateMixin ...