flutter - 如何用 Flutter 在 initState 函数中一一调用异步函数
问题描述
假设我想从后端服务器获取数据,并在 initState 中通过 post 方法调用 API。我想一一调用下面的函数。
Map response = {};
Map response2 = {};
void initState() {
callAPI_1();
callAPI_2();
ShowData();
}
void callAPI_1() async {
.
.
.
HttpClientResponse responseBody = await request.close();
this.setState((){
response = responseBody;
});
}
void callAPI_2() async {
.
.
.
HttpClientResponse responseBody2 = await request2.close();
this.setState((){
response2 = responseBody2;
});
}
void ShowData() {
print(response);
print(response2);
}
期望编程流程的顺序应该是initState -> callAPI_1 -> callAPI_1 -> ShowData;
关于如何实现它的任何建议?
解决方案
试试这个
Map response = {};
Map response2 = {};
void initState() {
asyncMethod();
}
asyncMethod() async{
await callAPI_1();
await callAPI_2();
await ShowData();
void callAPI_1() async {
.
.
.
HttpClientResponse responseBody = await request.close();
this.setState((){
response = responseBody;
});
}
void callAPI_2() async {
.
.
.
HttpClientResponse responseBody2 = await request2.close();
this.setState((){
response2 = responseBody2;
});
}
void ShowData() {
print(response);
print(response2);
}
推荐阅读
- outlook - 共享 Outlook 日历而不显示详细信息?
- mysql - 突然,我的实例停止响应 mysql 连接的传入连接
- sql - 如何在 SQLite 中显示我的表/关系的属性?
- c++ - 使用派生类的静态成员而不是基类
- html - 您可以创建下面给出的网页表结构:
- css - SVG 笔画无法与 CSS 变量一起正常工作
- maven - SonarQube “主分支没有代码行。” 詹金斯说分析成功时出现问题
- python - 自动化 Boring Stuff Lucky 批处理文件和命令行问题
- ansible - 有条件地连接 jinja2 列表
- stanford-nlp - stanfordnlp 差异 3.9.2 -> 4.0.0 changelg