我有一个scopedModel类,可以在其中获取数据。问题是我无法使用我拥有所有api请求的作用域模型从InitState方法呈现此数据。该方法正在被调用,但内部调用未被调用,因此页面的初始状态未正确显示。
void initState() {
print("Check initState");
super.initState();
ScopedModelDescendant<MainModel>(
builder: (BuildContext context, Widget child, MainModel model) {
print("Get into the scoped model");
model.fecthCars();
model.fecthCities();
model.fecthBuys(model.getUserDto.token);
print(model.getBuys().length);
return;
});
}
Run Code Online (Sandbox Code Playgroud)
没有任何fetches(Api请求)被调用。然后scopedModel返回一个小部件。我需要在第一次进入经理时进行更新,仅此而已。无需再次调用。这可能吗?还是应该在我需要的每个文件中对我的api请求进行硬编码?
更新
如果已经设置了作用域模型类,则可以在其内部设置一个Future。
mixin MyModel on Model {
Future<TypeToReturn> methodName(String param) async {
Uri uri = new Uri.http('serverUrl', 'api/call');
return await http.get(uri).then((http.Response response) {
final List<dynamic> myResponse= json.decode(response.body);
return myResponse;
}).catchError((error) {
print(error);
});
}
}
Run Code Online (Sandbox Code Playgroud)
事后准备,您可以设置FutureBuilder
Widget _buildBody(BuildContext context, MainModel model) {
return FutureBuilder(
future: model.methodName(someString), //This is the method name …Run Code Online (Sandbox Code Playgroud)