【问题标题】:How to finish the async Future task before executing the next instruction Flutter如何在执行下一条指令 Flutter 之前完成异步 Future 任务
【发布时间】:2019-03-01 20:00:01
【问题描述】:

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

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

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

编辑:添加代码来解释

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,
            );
          }
        }
    }
  }

【问题讨论】:

  • 如何等待?使用await
  • 更多关于awaithere

标签: asynchronous dart flutter dart-async


【解决方案1】:

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

例如:

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

在 someFutureFunction 返回某些内容之前,您的代码块不会运行。

【讨论】:

  • 简洁明了的答案
【解决方案2】:

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

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

另一个函数将使用 JSON 内容并将格式转换为模型并返回到类。

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;
}

在类中的使用,定义了一个从 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. 
}

希望这会有所帮助。

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-16
      • 1970-01-01
      • 2017-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多