Flutter State & Scoped Model Approach
ApproachThis approach removes most of the requirements to use Stateful Widgets, enabling the user to use Stateless Widgets instead in many cases.
ScopedModel has been mentioned in many articles as an alternative to just using InheritedWidget. At first sight, it looks like the ScopedModel package is basically InheritedWidget, only made easier to use.
PackageScopedModel is a Dart package and it is available here: https://pub.dartlang.org/packages/scoped_model
As it is a package you will have to install it:
https://pub.dartlang.org/packages/scoped_model - -installing-tab-
Package ReadmeThe package README.md file includes the following text:
A set of utilities that allow you to easily pass a data Model from a parent Widget down to its descendants. In addition, it also rebuilds all of the children that use the model when the model is updated. This library was originally extracted from the Fuchsia codebase.
This package provides three main classes:
1. ModelYou will extend this class to create your own Models, such as SearchModel or UserModel.
You can listen to Models for changes!
2. ScopedModel Widget.If you need to pass a Model deep down your Widget hierarchy, you can wrap your Model in a ScopedModel Widget.
This will make the Model available to all descendant Widgets
3. ScopedModelDescendant Widget.
Use this Widget to find the appropriate ScopedModel in the Widget tree.
It will automatically rebuild whenever the Model notifies that change has taken place.
Multiple ModelsAt first glance, it looks as if this package allows the user to use multiple State Models. This certainly makes it a better candidate for working with larger applications. You could have User data in one model, Transaction data in another etc.
Exercise – ‘state_and_scoped_model’The code below is not perfect by any means (you can add the same car twice and when you tap on it, it selects both) but it demonstrates how to get an app up and working with ScopedModel and how you can maintain separate states in separate models.
In this exercise, I use the ScopedModel to handle two separate state
1. a list of cars (to which we can add cars)
2. the currently selected car (which you can change by tapping on a car).
There is more code for you to copy and paste in this example.
However, this app does more than some of the previous examples: it allows you to add cars and allows you to select cars.
Step 1 – Create Default Flutter App
Follow the instructions in Generate Your First App Leave project open.
Step 2 – Replace Application Code
Replace contents of file ‘main.dart’ in folder ‘lib’ with the following:
Step 3 – Open Emulator & Run
Follow the instructions in Open Android Emulator & Run Your First App
If you tap on the ‘+’ button at the bottom it adds another car.
If you tap on a car it selects the car (adding a blue background) and sets the text of the selected car at the bottom.