The Scoped model architecture is a great option for state management in flutter. I absolutely love it, and here’s why you should too!

🔥🔥🔥🔥

Model

The model is a class where you can listen to changes and define your model. You can have one or as many Models you’d like. It would be more efficient to make models for example User Authentication, User Feed, TextController, AnimationControllers etc. Keeping all these models separate and listening to changes accordingly.

Example of a Model

As you can see in our UserModel the value for userName is empty. So what if we want to update the value of userName? With the changeName() method! The method has a String parameter of newValue which we then set to _userName. Then notify all the listeners of the new value with notifyListeners(). Pretty simple right? Here’s what it looks like step by step.

The value of userName is empty. We set _userName to the new value passed by changeName(String newValue) Notify all the listeners of the new value. Widgets scoped to UserModel rebuild after being notified.

ScopedModel

Put this at the root of your application. Think of this as like a store connector from redux.

ScopedModelDescendant

This is a Widget to find the appropriate Model in the Widget tree. It will automatically rebuild whenever the Model notifies that change has taken place. When a widget is wrapped in a ScopedModelDescendant the children will update to changes in the Model.

Example of ScopedModel/ScopedModelDescendant

So this is the boilerplate to user Scoped Model but this doesn’t allow us to change the value of userName. Let’s see how we would do that.

It’s as easy as that! This is why I love ScopedModel, it is very easy to read. Of course this is all personal preference but if you’re new to flutter give ScopedModel a try.

I’ll be writing a post on how to have multiple models and class parameters in an app soon! Hopefully you liked this post :)