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:
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.
Now that we have a custom state attached to our controller, let’s write the function to fetch user data from the database.
Let’s introduce the change method. We use the change method to change the state of the controller. Here’s how it works:
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 provides all these states in the form of RxStatus. We provide the status while changing the controller’s state. Take a look at the code below:
We have successfully ...