【问题标题】:how to get the future result in whenComplete如何在whenComplete中获得未来的结果
【发布时间】:2021-06-14 09:25:34
【问题描述】:

现在我正在使用此代码从服务器获取 api 响应,当响应完成时,我想做一些逻辑,这是我的代码:

Future<Response> res= refreshAuthToken(dio, userName, password, response);
        res.whenComplete(() => {
         storage.write(key: "refreshTimes", value: "0")
        });
        return res;

首先我向服务器发送一个http请求,然后当响应完成时,我想做一些符合Response的逻辑,最后返回Future结果。但我的问题是我不知道如何在 whenComplete 函数中获取响应结果,是否可以在 whenComplete 中使用响应结果?如何得到他的回应?喜欢:

res.whenComplete((response) => {
      storage.write(key: "refreshTimes", value:response.getxxxxxx")
 });

【问题讨论】:

  • 使用 then((response) {...}) 代替 whenComplete()。如果您不关心未来的价值,则使用 whenComplete() 是一个好习惯,否则使用 then()。 Future&lt;R&gt; then&lt;R&gt;(FutureOr&lt;R&gt; onValue(T value), {Function? onError});

标签: flutter


【解决方案1】:
await refreshAuthToken(dio, userName, password, response).then((Response res) {
   // add your logic here.
})

【讨论】:

    【解决方案2】:

    您可以使用then() 代替whenComplete()

    例如-

    MyFutureExample().then((response) {
      // add the logic in here
    });
    

    then()MyFutureExample() 完成时按照其逻辑触发。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-29
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 2018-08-23
      • 2012-04-02
      • 2014-04-25
      • 1970-01-01
      相关资源
      最近更新 更多