Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Dart, how to pass a function as parameter that returns a Future

Tags:

flutter

dart

I'm trying to pass as parameter of a method, a function that returns Future<Response>.

I tried to do

Future<String> _execute(Function<Future<Response>>() function) async { }

but it does not even compile.

What's the correct syntax?

like image 761
StackOverflower Avatar asked Jan 07 '20 03:01

StackOverflower


2 Answers

You can do it like this,

Future<String> _myFunction(Future<Response> Function() function) {
  ...
}
like image 75
Crazy Lazy Cat Avatar answered Nov 13 '22 20:11

Crazy Lazy Cat


You just need to specify that your parameter is a Function:


Future<bool> kappa() async{
  await Future.delayed(Duration(seconds: 1));
  return true;
}
​
Future<bool> foo(Function f) async{
  var k = await f();
  return k;
}
​
void main() async{
   print(await foo(kappa));
}

This will print true. In your case, your function parameter can be:

Future<String> _execute(Function function) async { }
like image 20
Ademir Villena Zevallos Avatar answered Nov 13 '22 22:11

Ademir Villena Zevallos