首页 > 解决方案 > 等待直到另一个异步函数完成

问题描述

我是 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),
              ))
        ],
      ),

标签: dartflutter

解决方案


只需使用关键字调用该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),
          )
        )
      ],
    ),
  );
}

推荐阅读