我不知道这段代码中发生了什么:
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.
型
我甚至听说你不能有任何未来类型。是因为这样的错误显示在这里吗?
2条答案
按热度按时间wd2eg0qa1#
当您这样做时:
字符串
声明
fnct2
返回Future
(这是Future<dynamic>
的简写)。在fnct2
的主体中,调用Future.then(...)
返回的Future
被忽略,fnct2
不等待,fnct2
* 立即 * 返回。由于没有显式的return语句,它隐式返回null
。也就是说,你的代码相当于:型
由于
fnct2
的返回类型是Future<dynamic>
并标记为async
,因此其主体中的任何return
语句都将被推断为dynamic
。dynamic
禁用静态类型检查,因此允许返回任何内容(包括nothing或null
),无论是隐式还是显式。async
关键字应用语法糖,使其等效于:型
现在,如果
fnct2
没有async
关键字,省略显式的return
语句将等效于:型
其中它现在隐式返回
null
而不是Future<dynamic>.value(null)
。fnct2
被声明为返回非null
Future
,因此不允许隐式返回null
。w80xi6nr2#
字符串
函数
fnct2
返回Future,它标记为future c,所以默认返回类型是Future<dynamic>
。但是一旦你删除了fixc,默认的返回类型就变成了
null
,并且函数期望返回一个Future。所以在这个例子中你可以使用任何一个,
型
将Future标记为可空,
型
希望这能帮上忙。