Fat Arrow是语法糖 - 但不会返回

问题描述 投票:2回答:1

Fat Arrow是语法糖,就像here所描述的那样

但是,如果我删除了返回(寻找:future.then(print); // << Removed return),那么它会抱怨缺少回报?:

嗯,或者我错过了“回归”的事情......

import 'dart:async';

main() {
  printsome();
  print("After should be called first...");
}

Future<void> printsome() {
  final future = delayedFunction();
  future.then(print); // << Removed return
  // You don't *have* to return the future here.
  // But if you don't, callers can't await it.
}

const news = '<gathered news goes here>';
const oneSecond = Duration(seconds: 1);
Future<String> delayedFunction() =>
    Future.delayed(oneSecond, () => news);

我收到这个警告:

[dart] This function has a return type of 'Future<void>', but doesn't end with a return statement. [missing_return]
dart
1个回答
1
投票

=> expr隐式返回expr的结果,所以如果你想用函数体{ return expr; }替换它,你需要添加return,否则将隐式返回null

您声明了一个返回类型为Future<void>的函数,DartAnalyzer警告您函数没有返回这样的值。

你可以添加async,使函数隐式返回一个Future

Future<void> printsome() async {
  final result = await delayedFunction();
}

或者如果你不想使用async,你可以添加return

Future<void> printsome() {
  final future = delayedFunction();
  return future.then(print); // return the Future returned by then()
}
© www.soinside.com 2019 - 2024. All rights reserved.