Flutter Dart函数作为另一个函数的参数

问题描述

我正在查看文档,但未能找到问题的答案:

假设我有一个函数,返回一个我想嵌入第二个函数Future<String>,该函数可以采用Future<String>类型的任何其他函数,语法为-如果我没有记错-将是:

String functionTwo(Future<User> Function() putFunctionHere) async {
  await code
  return 'some string';
}

如果我不得不猜测Dart语法,那就是:

String functionTwo(Function putFunctionHere){...}

哪个让我想到了我的问题,为什么我们必须指定Future<User> Function()是唯一的方法

为什么我们必须将括号放在Function

旁边

解决方法

语法如下:

OutputType Function(ParameterType1 paramater1,ParameterType2 parameter2...) nameOfFunctionForUsageInsideTheMethod

因此可以理解以下内容,我们将一个函数用作参数,该函数必须返回Future<User>并且不带参数。

Future<User> Function() putFunctionHere

此函数可以这样称为putFunctionHere

final value = await putFunctionHere()