dart - 等待直到另一个异步函数完成
问题描述
我是 Flutter 的新手。我正在调用一个async
函数来从服务器获取数据。我的代码Navigator.push()
必须在异步onEdit()
函数完成后执行。但对我来说,在完成Navigator.push()
之前执行onEdit()
。
代码:
void onEdit()async {
value= await getJson();
print(value);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color.fromRGBO(33, 64, 95, 1.0),
leading: Icon(Icons.chevron_left),
actions: <Widget>[
FlatButton(
onPressed: (){
onEdit();
Navigator.push(context, MaterialPageRoute(builder: (context) => new Case(value)) );
},
child: Text(
"Edit",
style: TextStyle(color: Colors.white),
))
],
),
解决方案
只需使用关键字调用该onEdit
函数。await
Future<void> onEdit() async {
value = await getJson();
print(value);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color.fromRGBO(33, 64, 95, 1.0),
leading: Icon(Icons.chevron_left),
actions: <Widget>[
FlatButton(
onPressed: () async {
await onEdit();
Navigator.push(context, MaterialPageRoute(builder: (context) => new Case(value)) );
},
child: Text(
"Edit",
style: TextStyle(color: Colors.white),
)
)
],
),
);
}
推荐阅读
- html - 如果点击html中的复选框,点击按钮,需要跳转到下一页,但是没有
- maven - 将工件上传到 Artifactory 时,管道写入失败
- d3.js - 在 D3 V5 中在轴刻度上设置标签
- sparql - sparql 查询使用数据值获取特定类的所有个体
- python - 在 Visual Studio Code 中使用 pandas 的问题
- autohotkey - Autohotkey / AHK - 字符串作为不带“”的函数参数
- html - Page-Break-Before:在 Edge 84 浏览器中无法正常工作
- r - 使用所有列 NA 过滤 data.frame 但在某些为 NA 时保留
- c# - 在 C# 中使用 oracle 客户端选择非英语字符
- javascript - Uncaught (in promise) TypeError: Fetch on Window。快递服务器