【问题标题】:Future<void> vs void未来<void> vs void
【发布时间】:2020-01-21 01:24:01
【问题描述】:

假设我想创建一个异步方法。我可以将其返回类型设为 Future void 或简单地“void”(如下面的示例所示)。两种方法似乎都可以解决问题。那么两者有什么区别呢?我什么时候应该使用 Future void 而不是 void?谢谢!

Future<void> myMethod() async{ 
  await myOtherMethod(); //myOtherMethod() has return type of Future<void>
  print('something'); 
}

void myMethod() async{ 
  await myOtherMethod(); //myOtherMethod() has return type of Future<void>
  print('something'); 
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    在你想要的地方使用Future&lt;void&gt;

    调用未来函数:

    myMethod().then((_) => ...).catchError((err) => ...);
    

    使用await 以获得更易读的异步代码。

    await myMethod();
    await anotherMethod();
    

    使用void 在你想开火和忘记的地方。

    myMethod();
    ... do other stuff
    

    Future&lt;void&gt; 更为常见。如果您不确定要使用哪一个,请使用Future&lt;void&gt;

    【讨论】:

    • 这回答了我的问题!谢谢!
    【解决方案2】:
    Future<void> myMethod() async{ } 
    

    是一个异步函数,这意味着它让应用程序在等待某些操作完成时工作(例如:网络请求)。Future fun();当我们需要执行会在未来产生结果的操作时使用,例如网络调用。

    void fun(){};
    

    是一个不返回任何东西的函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-11
      • 2018-07-28
      • 1970-01-01
      • 2019-09-21
      • 2011-08-08
      • 2023-03-23
      • 2011-05-30
      • 1970-01-01
      相关资源
      最近更新 更多