1

I was looking into the documentation and failed to find an answer to my question:

Suppose I have a function the returns a Future<String> that I want to imbed in a second function which could take any other function that is of type Future<String>, the syntax -if I am not wrong- would be:

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

If I had to guess with regards to Dart syntax, I would say that it would be:

String functionTwo(Function putFunctionHere){...}

Which leads me to my question, why do we have to specify Future<User> Function() is it the only way?

And why do we have to put the parentheses next to Function

  • 1
    Some part of your question is answered in this link [enter link description here](https://stackoverflow.com/questions/43334714/pass-a-typed-function-as-a-parameter-in-dart) – Arindam Ganguly Aug 13 '20 at 19:17
  • Does this answer your question? [DART: Passing function in a function as parameter](https://stackoverflow.com/questions/62550421/dart-passing-function-in-a-function-as-parameter) – Sanjay Sharma Aug 13 '20 at 19:22
  • @ArindamGanguly thank, although partially, it still answers some of my questions. Thank you. –  Aug 13 '20 at 19:24
  • @SanjaySharma I am sorry, but it doesn't, thank you for the input anyways. –  Aug 13 '20 at 19:27
  • Does this answer your question? [Pass a typed function as a parameter in Dart](https://stackoverflow.com/questions/43334714/pass-a-typed-function-as-a-parameter-in-dart) – deHaar Aug 14 '20 at 11:56

1 Answers1

1

The syntax are as follow:

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

So the following can be read we take a function as argument which must return Future<User> and takes no arguments.

Future<User> Function() putFunctionHere

This function can then be referred to as putFunctionHere like:

final value = await putFunctionHere()
julemand101
  • 28,470
  • 5
  • 52
  • 48
  • If I do understand correctly, I can avoid specifying the return type of the embedded function if I want, right? But if I do specify ```Future``` I find myself forced to add the parentheses to ```Function```, any idea as to why that happens? –  Aug 13 '20 at 19:27
  • You should always specify a return value but if you don't care about the return value you can use `void`, The parentheses is important since it is part of the syntax. The syntax `(Function method)` does in fact mean that you can a object as input which implements the interface `Function`. This is something entirely else and is properly not what you want. This class is documented here: https://api.dart.dev/stable/2.9.1/dart-core/Function-class.html – julemand101 Aug 13 '20 at 19:35