在以下方面的主要区别是:
Future<void> function(){}Future<Null> function(){}void function() {}funtion(){}有时,在调用API时,我使用了future或future,但我不知道主要的区别是什么,什么时候才是使用它的合适时间?
发布于 2021-04-16 04:39:36
默认情况下,像
null指针值。当您的函数没有返回任何内容并且没有标记为async时,请使用此原型
function() { // <- not async
// ... some code
// ... don't use return
}可以选择使用
function() {}上是一样的,但是如果您在调用后尝试分配一个值,您将在编译时得到一个错误:Error: This expression has type 'void' and can't be used.
就我个人而言,如果您真的没有返回值,而且函数不是异步的,我建议采用这种方法。请注意,您可以在正常和异步函数中使用void。
Future<void> function() async {}这样的函数用于返回Future<void>对象的异步函数。我个人建议,只有在不使用await ot then进行函数调用时,才推荐使用Future <void> function() async {},否则使用Future <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');
}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');
}Future<Null> function() async {}的函数返回Future<null>对象。无论何时返回null,都要使用它。不建议使用它,因为类Null不是从Object扩展的,您返回的任何内容都会标记一个错误(除了返回空值或显式空值的语句外):Future<Null> myFunction() async {
await Future.delayed(Duration(seconds: 2));
print('Hello');
// Ok
return (() => null)();
// Ok
return null;
}发布于 2021-04-16 06:23:34
Future<void> function() {}定义一个异步函数,该函数最终不返回任何内容,但可以在最终完成时通知调用方。另见:What's the difference between returning void vs returning Future?
Future<Null> function() {}定义一个异步函数,在它最终完成时最终返回null。不要使用这个;这是一个古老的Future<void>形式。它早于Dart 2,并且是必要的,因为void还不是一个合适的类型,并且没有任何机制来指示Future不应该返回任何内容。另见:Dart 2: Legacy of the void
void function() {}定义一个不返回任何内容的函数。如果该函数执行异步工作,调用方将无法直接判断它何时完成。
function() {}使用未指定的返回类型定义函数。返回类型隐式为dynamic,这意味着函数可以返回任何内容。不要这样做,因为它没有传达意图;读者将无法判断返回类型是有意还是无意中被省略的。它还将触发always_declare_return_types lint。如果您实际上想返回一个dynamic类型,则应该显式地使用dynamic function() {} .。
https://stackoverflow.com/questions/67118841
复制相似问题