在 ScopedModel 的文档中,有这些说明来检索先前创建的没有 ScopedModelDescendant 的 ScopedModel。我不知道我是否可以完全摆脱 ScopedModelDescendant 或者我应该最后一次在某个地方声明它?
从文档:
寻找模型#
有两种方法可以找到 ScopedModel Widget 提供的模型。
Use the ScopedModelDescendant Widget. It will find the Model and run the builder function whenever the Model notifies the listeners. Use the ScopedModel.of static method directly. To make this method more readable for frequent access, you can consider adding your own of
方法到您自己的模型类,如下所示:
class CounterModel extends Model { // ... /// 为这个 [Model] 包装 [ScopedModel.of]。static CounterModel of(BuildContext context) => ScopedModel.of(context); }
我不会使用 ScopedModelDescendant,所以我在根目录中实例化了 ScopedModel:
@override
Widget build(BuildContext context) {
return ScopedModel<TeamModel>(
model: TeamModel(widget._team),
child: Container(
...
))
我创建了一个静态方法,如文档中所示:
class TeamModel extends Model {
static TeamModel of(BuildContext context){
var of = ScopedModel.of<TeamModel>(context);
return of;
}
}
但我无法检索容器内的模型,它给出了著名的错误消息:
22:38:41.603 11 info flutter.tools I/flutter ( 9749): Error: Could not find the correct ScopedModel.
22:38:41.603 12 info flutter.tools I/flutter ( 9749):
22:38:41.603 13 info flutter.tools I/flutter ( 9749): To fix, please:
22:38:41.603 14 info flutter.tools I/flutter ( 9749):
22:38:41.604 15 info flutter.tools I/flutter ( 9749): * Provide types to ScopedModel<MyModel>
22:38:41.604 16 info flutter.tools I/flutter ( 9749): * Provide types to ScopedModelDescendant<MyModel>
22:38:41.604 17 info flutter.tools I/flutter ( 9749): * Provide types to ScopedModel.of<MyModel>()
22:38:41.604 18 info flutter.tools I/flutter ( 9749): * Always use package imports. Ex: `import 'package:my_app/my_model.dart';
从文档中我不清楚我是否应该使用ScopedModelDescendant
,否则我的代码有什么问题?