1

I've been playing with Scoped Model recently and was wondering if there's a better way to push multiple models onto the tree for use by children.

Suppose I have a 'AppModel' that's a composition of all the Models I need

class AppModel extends Model
{
  ModelA a = new ModelA();
  ModelB b = new ModelB();
  ModelC c = new ModelC();
}

I start by adding this model to the tree from main

runApp(ScopedModel<AppModel>(
    model: AppModel(),
    child: MaterialApp(
      title: 'MyApp',
      home: Home(),
    )),);

This causes the application to start at a Home page with an AppModel available in the tree

The Home page is a series of buttons each leading to another page which may use several of the models from AppModel

When a button is pressed I want to open the relevant page and pass the 'sub-models' that are needed from AppModel

Currently I have the onPressed for my buttons looking something like this, where I nest Scoped Models

() => Navigator.push(context, 
      MaterialPageRoute(builder: (context) => ScopedModel<ModelA>
          model: ScopedModel.of<AppModel>(context).a,
          child: ScopedModel<ModelB>(
             model: ScopedModel.of<AppModel>(context).b,
             child: PageAB())))))),

Within PageAB I can these access the relevant model via ScopedModel.of()

ScopedModel.of<ModelA>(context).modelAGet
ScopedModel.of<ModelA>(context).modelAFunc()

ScopedModel.of<ModelB>(context).modelBGet
ScopedModel.of<ModelB>(context).modelBFunc()

Is this the correct way to share (multiple) models? Or is there a more elegant solution?

4

1 回答 1

9

这是你可以做到的一种方式。我使用 Mixins 将不同的行为/功能编译到 AppModel 中。每个模型负责应用程序中的一个部分/功能。例如,我有一个 UserModel、SettingsModel 和 ContentModel

它们都是 ScopedModel 库中 Model 类的 mixin

mixin UserModel on Model {
 ...
}
mixin SettingsModel on Model {
 ...
}
mixin ContentModel on Model {
 ...
}

然后我的主要 AppModel 看起来像这样

class AppModel extends Model with UserModel, SettingsModel, ContentModel {
  ...
}

通过这种方式,我组合了来自不同模型的行为,如果您只想公开一种类型的模型,您可以转换它并使用该接口。

我目前倾向于这种方式,其中模型文件管理某些功能的所有状态,并且在这些模型中,我注入作为单例实例的服务,以便在需要时在它们之间共享信息。这些服务执行我所有的实际业务逻辑,连接到 API,序列化并编译为我的应用程序的上下文信息。

于 2019-03-01T11:09:37.253 回答