我有一个 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;
});
}
没有调用任何获取(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);
});
}
}
Aftermards 你可以设置你的 FutureBuilder
Widget _buildBody(BuildContext context, MainModel model) {
return FutureBuilder(
future: model.methodName(someString), //This is the method name above
builder: (context, AsyncSnapshot<TypeToReturn> snapshot) { //type u return
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
} else {
if (snapshot.data.length == 0)
return Center(
child: Text(
"No Data Found",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 16.0,
),
),
);
return (create your own widget with the data inside the snapshot)
}
},
);
}
希望这能更清楚地说明我是如何做到的。
最佳答案
我偶然发现了以下解决方案:
在我的 StatefulWidget 的 State 类中:
@override
void initState() {
super.initState();
// and here...
MyModel model = ScopedModel.of(context);
// now I can do with the model whatever I need to do:
Text someVar = model.initialText;
model.getValuesFromSomewhere();
// and so on
}
在我看来,这是解决原始问题所述问题的最简单方法。
https://stackoverflow.com/questions/51883755/