Flutter Future<void> vs Future<Null> vs void

Naz*_*zar 5 dart flutter

之间的主要区别是什么:

  1. Future<void> function(){}
  2. Future<Null> function(){}
  3. void function() {}
  4. funtion(){}

有时我在调用 API 时使用 void 或 future ,但我真的不知道主要区别是什么,什么时候使用它是正确的?

jam*_*lin 8

  1. Future<void> function() {}

    定义一个异步函数,该函数最终不返回任何内容,但可以在最终完成时通知调用者。另请参阅:返回 void 与返回 Future 有什么区别?

  2. Future<Null> function() {}

    定义一个异步函数,null当它最终完成时最终返回。不要使用这个;这是 的古老形式Future<void>。它早于 Dart 2 并且是必要的,因为void还不是一个合适的类型,并且没有机制表明 aFuture应该不返回任何内容。另请参阅:Dart 2: Legacy of thevoid

  3. void function() {}

    定义一个不返回任何内容的函数。如果函数执行异步工作,调用者将无法直接知道它何时完成。

  4. function() {}

    定义具有未指定返回类型的函数。返回类型是隐式的dynamic,这意味着该函数可以返回任何东西。不要这样做,因为它没有传达意图;读者将无法判断是否有意或无意地省略了返回类型。它也会触发always_declare_return_typeslint。如果你真的想返回一个dynamic类型,你应该明确地使用dynamic function() {}


Ign*_*ior 3

  1. 默认情况下,函数喜欢function() {}返回一个null指针值。当您的函数不返回任何内容并且未标记为时,请使用此原型async
function() { // <- not async
 // ... some code
 // ... don't use return
}
Run Code Online (Sandbox Code Playgroud)
  1. 或者,您可以使用void function() {}sintaxis 指定不返回值。它是相同的,function() {}但如果您在调用后尝试分配一个值,您将在编译时收到错误:

Error: This expression has type 'void' and can't be used.

就我个人而言,如果您确实没有返回值并且该函数不是异步的,我建议您使用这种方法。void请注意,您可以在普通函数和异步函数中使用。

  1. 函数喜欢Future<void> function() async {}是返回一个Future<void>对象的异步函数。

我个人建议仅当您在调用函数时void function() async {}不使用awaitot时,否则使用.thenFuture <void> function() async {}

一个例子:

Future<void> myFunction() async {
  await Future.delayed(Duration(seconds: 2));
  print('Hello');
}

void main() async {
  print(myFunction()); // This works and prints 
                     // Instance of '_Future<void>'
                     // Hello
  // Use this approach if you use this:
  myFunction().then(() {
    print('Then myFunction call ended');
  })

  // or this
  await myFunction();
  print('Then myFunction call ended');
}
Run Code Online (Sandbox Code Playgroud)
void myFunction() async {
  await Future.delayed(Duration(seconds: 2));
  print('Hello');
}

void main() async {
  print(myFunction()); // This not works
                     // The compile fails and show
                     // Error: This expression has type 'void' and can't be used.
  // In this case you only can call myFunction like this
  myFunction();

  // This doesn't works (Compilation Error)
  myFunction().then(() {
    print('Then myFunction call ended');
  });

  // This doesn't works (Compilation Error)
  await myFunction();
  print('Then myFunction call ended');
}
Run Code Online (Sandbox Code Playgroud)
  1. 函数喜欢Future<Null> function() async {}返回一个Future<null>对象。每当您返回时都可以使用它null。不建议使用它,因为类Null不是扩展自的Object,并且您返回的任何内容都会标记错误(返回 null 或显式 null 值的语句除外):
Future<Null> myFunction() async {
  await Future.delayed(Duration(seconds: 2));
  print('Hello');

  // Ok
  return (() => null)();
  
  // Ok
  return null;
}
Run Code Online (Sandbox Code Playgroud)