I. Introduction to ScopedModel

ScopedModel is an entry-level state management framework with a simple concept that can be easily understood by referring to official documentation.

It is necessary to lift state up in a Flutter. Lifting state can be understood as the idea of extracting states shared by components and managing them at a higher level. The ScopedModel provides convenience for this state management.

2. Three concepts in ScopedModel

ScopedModel has three important concepts and three classes: Model, ScopedModel, and ScopedModelDescendant. The ScopedModel basically implements its functionality through these three classes.

The Model is where the state and state operations are encapsulated. We can store the desired data in the Model and put methods for manipulating the data, such as adding and deleting, here. The Model also provides a notifyListeners method, which can be called to notify the interface of changes made to the data.

The ScopedModel is a Widget for saving the Model. A ScopedModel is usually used as a parent layout for an application entry and passed Model as a parameter, making the ScopedModel hold the Model.

In the ScopedModel sub-layout, the Model can be retrieved using the scopedModel.of

(context) method.

The ScopedModelDescendant, as its name suggests, is a descendant of the ScopedModel. Again, it’s a Widget. The ScopedModelDescendant exists as a sub-layout under the ScopedModel, and its main role is to respond to status updates.

The Builder function exists in the ScopedModelDescendant, which is called whenever a notifyListeners() of the Model occurs to generate an interface based on the data in the Model.

3. Practice of ScopedModel

Here is an example of a common get list select list. One page shows selected items and jumps to the list, and one page shows the list.

1. The introduction ofscoped_modelThird-party libraries

Add dependencies to the dependencies of the pubspec.yaml file in the root directory

dependencies: ... Scoped_model: ^ 1.0.0Copy the code

Definition 2.Model

Create a ListModel class that inherits the Model class from the scoped_Model package.

The ListModel class contains three states: list initialization flags, list data, and selected list items.

  bool _init = false; List<String> _list = []; // List data String _selected ='Not selected'; // The selected list itemCopy the code

There are not only data in the Model, but also methods to operate on the data. There are two methods defined here: selecting list items and loading list methods. After updating the data, notifyListeners() are called to notify the UI of updates.

/** * select list item */ void select(String selected) {_selected = selected; // Notice of data changes (); } /** * loadList */ void loadList() async {// await future.delayed (Duration(milliseconds: 3000)); _list = ['1. Scoped Model'.'2. Scoped Model'.'3. Scoped Model'.'4. Scoped Model'.'5. Scoped Model'.'6. Scoped Model'.'7. Scoped Model'.'8. Scoped Model'.'9. Scoped Model'.'10. Scoped Model'
    ];

    _init = true; // Notice of data changes (); }Copy the code

3. The UI layout

On the UI, use ScopedModel as the root layout to provide the Model, and use ScopedModelDescendant as the child layout to respond to the Model.

First, in the main() method, create a ListModel instance and wrap the MyApp layout with ScopedModel

void mainListModel = ListModel(); ListModel = ListModel(); // Use ScopedModel as the root layout runApp(ScopedModel(model: listModel, child: MyApp())); }Copy the code

To illustrate the concept of status promotion, the example uses two pages, a ShowPage and a ListPage. ShowPage is used to display selected list items and provides a jump to ListPage, which is used to load display lists.

In the ShowPage, the selected items in the ListModel are displayed.

ScopedModelDescendant<ListModel>(
  builder: (context, child, model) {
    String selected = model.selected;
    returnText(selected); }),Copy the code

The generic in the ScopedModelDescendant specifies the ListModel, which automatically retrieves the ListModel in the ScopedModel in builder: (Context, Child, Model), in which the model parameter is used to retrieve the state and build the UI.

Similarly, in the ListPage, load status and list are displayed via ScopedModelDescendant.

Body: ScopedModelDescendant<ListModel>(Builder: (context, child, model) {// Display interface by statusif(! Model.isinit) {// Display the loading interfacereturn buildLoad();
        } elseVar list = model.list;returnbuildList(list); }}),Copy the code

4. State changes

The ListPage is a StatefulWidget, so you can load the list in the initState() method.

@override
void initState() { super.initState(); ListModel model = ScopedModel.of<ListModel>(context); / / get ListModelif(! model.isInit) { model.loadList(); // Load list}}Copy the code

When you click on an item in the list, the item is selected, and the Select (String) method in the ListModel is called, returning to the previous interface.

onTap: () { ListModel model = ScopedModel.of<ListModel>(context); model.select(list[index]); // Return to navigator.pop (context); },Copy the code

The full code can be found at github.com/windinwork/…

4. Points to note in ScopedModel

  1. ScopedModelDescendantNeed to be as low as possible to avoid extensive UI rebuilding. Here is the official example.
// Error examplereturn ScopedModelDescendant<CartModel>(
  builder: (context, child, cart) {
    return HumongousWidget(
      // ...
      child: AnotherMonstrousWidget(
        // ...
        child: Text('Total price: ${cart.totalPrice}'),),); });Copy the code
// Correct examplereturn HumongousWidget(
  // ...
  child: AnotherMonstrousWidget(
    // ...
    child: ScopedModelDescendant<CartModel>(
      builder: (context, child, cart) {
        return Text('Total price: ${cart.totalPrice}'); },),),);Copy the code

Five, the summary

ScopedModel is a state management Model suitable for beginners to understand. It uses Model to save state and notify state changes, uses ScopedModel to provide Model, and uses ScopedModelDescendant layout to respond to state changes.

Refer to the directory

Simple app state management