The “Hello World” of Flutter’s scoped_model

Nick Manning
Flutter Community
Published in
2 min readFeb 12, 2019

What scoped_model does is it makes working with state in your app much easier.

Note: you can check out the video for this post here and the longer, pro video here.

While it’s all well and good to exclusively use StatefulWidget, most of the time your app is going to have multiple widgets that need to use the same shared state. The issue with this is that when those widgets exist in various places in our app, passing around state becomes pretty cumbersome.

In other words, scoped_model makes it easy for various widgets to access the same shared state.

There are also some nice additional benefits you get as well:

  • It allows us to conveniently consolidate app-wide state variables and business logic.
  • We can avoid reading up on overly complex architecture patterns.
  • Very minimal boilerplate code is required, compared to similar libraries.

How Does it Work, Exactly?

scoped_model consists of three concepts. First, it offers a Model class. We add whatever state variables we want as well as business logic as well. Next, for each screen that needs to access this state, we wrap everything with a single ScopedModel widget, referring to the instance of our model class we created. Finally, for any child-widgets that need to access our state (even if they're in separate files), we simply wrap them in a ScopedModelDescendant widget. Whatever is wrapped there can automagically react to our state updates.

What I love about this solution is there’s no complex architecture or a large amount of boilerplate code we have to maintain to achieve this.

Now let’s implement something simple so that makes more sense.

Terms We’ll Be Throwing Around

  • State: Data. In our case, state changes over time as users interact with the UI. One or more “stateful” widgets may re-render as state changes.
  • Model: A class that represents a “thing” in our app. Examples: User, Podcast, Episode, etc
  • Scoped Model: A class that holds state variables and contains business logic.
  • Business Logic: Code that affects data in our app, typically grouped by concern. Examples: The Business Logic that determines how we work with fetching and managing Podcasts in our app.
  • Render: The act of drawing something on the screen, i.e. a Button, Image, etc.

Let’s Dive In

Let’s create a simple app to demonstrate scoped_model. If you don't want to follow along, you can find the code here.

Our app will be a pretty contrived example in order to keep things simple. It will:

  • Show a screen with three simple text labels.
  • When the plus button at the bottom is tapped, our state is updated.
  • Because our labels are wired up to a Scoped Model, they’ll get those updates automagically.

Code Walk-Through

To continue with the step-by-step code walk through and video check out: https://fluttercrashcourse.com/blog/scoped-model-goto

Enjoy!

--

--