Future < dynamic>problem in flutter/dart .我只是想知道代码是如何在下面生成错误的

gtlvzcf8  于 5个月前  发布在  Flutter
关注(0)|答案(2)|浏览(55)

我不知道这段代码中发生了什么:

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.


我甚至听说你不能有任何未来类型。是因为这样的错误显示在这里吗?

wd2eg0qa

wd2eg0qa1#

当您这样做时:

Future fnct2() async {
  fnct().then((x) {
    print("inside then()");
  });
}

字符串
声明fnct2返回Future(这是Future<dynamic>的简写)。在fnct2的主体中,调用Future.then(...)返回的Future被忽略,fnct2不等待,fnct2 * 立即 * 返回。由于没有显式的return语句,它隐式返回null。也就是说,你的代码相当于:

Future<dynamic> fnct2() async {
  fnct().then((x) {
    print("inside then()");
  });
  return null;
}


由于fnct2的返回类型是Future<dynamic>并标记为async,因此其主体中的任何return语句都将被推断为dynamicdynamic禁用静态类型检查,因此允许返回任何内容(包括nothing或null),无论是隐式还是显式。
async关键字应用语法糖,使其等效于:

Future<dynamic> fnct2() {
  fnct().then((x) {
    print("inside then()");
  });
  return Future<dynamic>.value(null);
}


现在,如果fnct2没有async关键字,省略显式的return语句将等效于:

Future<dynamic> fnct2() {
  fnct().then((x) {
    print("inside then()");
  });
  return null; // ERROR
}


其中它现在隐式返回null而不是Future<dynamic>.value(null)fnct2被声明为返回非nullFuture,因此不允许隐式返回null

w80xi6nr

w80xi6nr2#

Future fnct2() async {
fnct().then((x){
print("inside then()");
});

字符串
函数fnct2返回Future,它标记为future c,所以默认返回类型是Future<dynamic>
但是一旦你删除了fixc,默认的返回类型就变成了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()");
});
}


希望这能帮上忙。

相关问题