该scoped_model
库旨在同时使用多个模型。这就是ScopedModel
andScopedModelDescendant
是泛型并具有类型参数的部分原因。您可以使用 Widget 树的顶部附近定义多个模型,然后使用ScopedModel<LoginModel>
和在树的较低位置使用这些模型。后代将根据他们的类型参数去寻找合适的模型。ScopedModel<NewsModel>
ScopedModelDescendant<LoginModel>
ScopedModelDescendant<NewsModel>
我拼凑了一个简单的例子。以下是模型:
class ModelA extends Model {
int count = 1;
void inc() {
count++;
notifyListeners();
}
}
class ModelB extends Model {
int count = 1;
void inc() {
count++;
notifyListeners();
}
}
这是我在应用程序中显示的内容:
ScopedModel<ModelA>(
model: ModelA(),
child: ScopedModel<ModelB>(
model: ModelB(),
child: ScopedModelDescendant<ModelA>(
builder: (_, __, a) => ScopedModelDescendant<ModelB>(
builder: (_, __, b) {
return Center(
child: Column(
children: [
GestureDetector(
onTap: () => a.inc(),
child: Text(a.count.toString()),
),
SizedBox(height:100.0),
GestureDetector(
onTap: () => b.inc(),
child: Text(b.count.toString()),
),
],
),
);
},
),
),
),
)
它似乎工作得很好。非嵌套方法也适用:
ScopedModel<ModelA>(
model: ModelA(),
child: ScopedModel<ModelB>(
model: ModelB(),
child: Column(
children: [
ScopedModelDescendant<ModelA>(
builder: (_, __, model) => GestureDetector(
onTap: () => model.inc(),
child: Text(model.count.toString()),
),
),
SizedBox(height: 100.0),
ScopedModelDescendant<ModelB>(
builder: (_, __, model) => GestureDetector(
onTap: () => model.inc(),
child: Text(model.count.toString()),
),
),
],
),
),
)