在ScopedModel的文档中,有以下说明可检索预先创建的没有ScopedModelDescendant的ScopedModel。我不知道是否可以完全摆脱ScopedModelDescendant,还是应该最后一次声明它?
从文档中
查找模型#
有两种方法可以找到ScopedModel提供的模型 小部件。
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
对您自己的Model类的方法如下:
Class CounterModel扩展了模型{// ... ///为此[Model]包装[ScopedModel.of]。 (BuildContext context)的静态CounterModel => 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
,否则我的代码有什么问题?