我不知道这部分代码发生了什么:
Future fnct() {
print("inside fnct()");
return Future.delayed(Duration(seconds:4),()=>"hello");
}
Future fnct2() async {
fnct().then((x){
print("inside then()");
});
在这里,即使不使用
await
关键字,此代码也可以完美运行。但是一旦我删除 async
关键字,就会出现错误:
The body might complete normally, causing 'null' to be returned, but the return type, 'Future<dynamic>', is a potentially non-nullable type.
我什至听说你不能有任何未来
Future fnct2() async {
fnct().then((x){
print("inside then()");
});
函数
fnct2
返回 Future 并标记为异步,因此默认返回类型为 Future<void>
。
但是一旦删除异步,默认返回类型就会更改为仅
null
并且函数期望返回 Future。
所以在这种情况下你可以使用其中任何一个,
Future fnct2() {
fnct().then((x){
print("inside then()");
});
return Future.value(0); // return some value
}
将 Future 标记为可为空,
Future? fnct2() {
fnct().then((x){
print("inside then()");
});
}
我希望这会有所帮助。