2

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

5
  • 1
    Some part of your question is answered in this link enter link description here Commented Aug 13, 2020 at 19:17
  • Does this answer your question? DART: Passing function in a function as parameter Commented Aug 13, 2020 at 19:22
  • @ArindamGanguly thank, although partially, it still answers some of my questions. Thank you. Commented Aug 13, 2020 at 19:24
  • @SanjaySharma I am sorry, but it doesn't, thank you for the input anyways. Commented Aug 13, 2020 at 19:27
  • Does this answer your question? Pass a typed function as a parameter in Dart Commented Aug 14, 2020 at 11:56

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

2 Comments

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<String> I find myself forced to add the parentheses to Function, any idea as to why that happens?
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: api.dart.dev/stable/2.9.1/dart-core/Function-class.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.