How to Use StateContainers in .NET MAUI to Manage State in Applications

rretamal
3 min read1 day ago

--

Example of Implementing StateContainers in .NET MAUI

How many times have you wanted to manage different states in your app? Maybe phrased like that, the answer is never, haha, so let’s break down the concept a bit.

Imagine you have an app where the user has access to certain modules depending on their subscription level or whether they’re logged in or not. With StateContainers, you can handle these kinds of situations efficiently.

So, what’s cool about this? Well, the cool part is that they are a type of structure that allows you to manage and store these states centrally, sharing data between pages without explicitly passing information during navigation.

What are the advantages?

  • Maintainability: By centralizing the state, the resulting code is more organized and easier to maintain.
  • Reactivity: State containers automatically notify views when the state changes.
  • Simplified Communication: They facilitate interaction between components that are not directly related in the navigation hierarchy.
  • Reusability: The same container can be used across multiple components or pages.

If you check the documentation, there are many more advantages, but these in particular seemed interesting to me.

But an article without a demo doesn’t work, so let’s do it! Let’s create a small demo where we control the user’s state, i.e., whether they are authenticated or not.

Let’s open Visual Studio and create a new solution for .NET MAUI, and give it an impactful name that totally describes what we want. In my case: StateContainersDemo.

Now that we have our solution created, we need to make sure we have the Community Toolkit installed. You can install it from the NuGet view or using this command:

Install-Package CommunityToolkit.Maui

Next, our MauiProgram.cs file should look like this:

Seguidamente tendremos que crear dos carpetas una para los modelos (Models) y otra para las vistas (Views).

El modelo con el que manejaremos el estado luce de la siguiente manera:

Next, we create a ContentPage for login called: LoginPage.xaml

Here, as you can see, we are handling three states: an initial state where the user enters their credentials, followed by a “Loading” state where we simulate the authentication process, and finally a “Success” state where the user is logged into the system.

To simulate the login, we’ll create a LoginViewModel file in our ViewModels folder, which should look like this:

Remember to inject it in the LoginPage.xaml.cs file like this:

As I mentioned earlier, this can be implemented in many places where we used to handle things manually, so it’s always a good idea to check out what libraries currently offer and focus more on the business logic rather than the implementation details.

You can find the code here:

Happy Coding!

--

--