如何在执行下一条指令之前完成异步 Future 任务 Flutter

How to finish the async Future task before executing the next instruction Flutter

我对我的数据库进行了一个函数调用,它在获取数据后更新了一个本地对象并花费了一些时间。

由于异步任务,程序移动到下一行代码。不幸的是,我需要通过下一行代码的异步调用更新的本地对象。

如何在执行下一段代码之前等待我的异步任务完成?谢谢

编辑:添加代码来解释

updateUser() {
return FutureBuilder(
        future: updateUserData(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState != ConnectionState.done) {
            return Text("hello not");
          } else {
            return Text('Hello!');
          }
        },

);}

  @override
  Widget build(BuildContext context) {
    switch (_authStatus) {
      case AuthStatus.notSignedIn:
        return new LoginPage(
          auth: auth,
          CurrentUser: CurrentUser,
          onSignedIn: _signedIn,
        );
      case AuthStatus.signedIn:
        {
          updateUser(); //THIS TAKES A COUPLE SECONDS TO FINISH BUT I NEED TO SEND IT TO THE NEXT PAGE

            return new HomePage(
              auth: auth,
              CurrentUser: CurrentUser,
              onSignedOut: _signedOut,
            );
          }
        }
    }
  }

您可以在 async 函数中使用 await 关键字。

例如:

  void someFunc() async {
    await someFutureFunction();
    // Your block of code
  }

这里你的代码块不会 运行 直到 someFutureFunction returns something.

这可能会有所帮助,下面的示例代码有两个功能, 下面的函数用于加载资产和 return JSON 内容。

Future<String> _loadCountriesAsset() async {
  return await rootBundle.loadString('assets/country_codes.json');
}

另一个函数将使用 JSON 内容并将格式转换为模型,将 return 转换为 class。

Future<List<CountryCode>> loadCountryCodes() async {
  String jsonString = await _loadCountriesAsset();
  final jsonResponse = json.decode(jsonString);
  // print(jsonResponse);

  CountriesCodeList countriesCodeList =
      new CountriesCodeList.fromJson(jsonResponse);
  // print("length " + countriesCodeList.codes.length.toString());
  return countriesCodeList.codes;
}

class 中的用法定义了从 services.dart 文件调用 loadCountryCodes() 函数的方法。

Future getCountryCodes() async {
var countryCodesList = await loadCountryCodes();

print("**** length " + countryCodesList.length.toString());
// Perform the operations, or update to the UI or server. It should be same for API call as well. 
}

希望这对您有所帮助。

您还可以使用自定义异步函数,如下例所示:

(() async {
   await restApis.getSearchedProducts(widget.sub_cats_id,widget.keyword).then((val) => setState(()
   {
      setState(() {
         data = val["data"];
      });
   }));
})();