0

I'm trying to understand how dart uses a function as parameter. I wrote this code...

typedef Future<String> myFunction();

void main() {
  A a = A();
  a.f1(a._f1);
}

class A {
  f1(myFunction func) async {
    String x = await _f1;
    print(x);
  }

  Future<String> _f1() {
    Future.delayed(Duration(seconds: 3)).then((f) {
      return "test";
    });
  }
} 

I need the function f1 returns "test", but I have this error : A value of type 'Future Function()' can't be assigned to a variable of type 'String'

If I change String x = await _f1 by Future x = await _f1 I have another error.. I tried a lot of combinations, all of them fail.

Can someone fix my code? Thank you.

2 Answers 2

1

The problem is this line:

String x = await _f1;

The parameter for the method is func, so you are referencing the _f1 method directly here rather than the parameter. Furthermore, rather than calling the method you are just referencing the method directly. In essence, you are trying to assign a Function to a variable that expects a String, which is what the error message is trying to tell you.

You need to reference the parameter and then you need to call it.

String x = await func();

As an aside, your _f1 method is currently returning null. This is because you are returning a value from the method within the then but you aren't returning anything to _f1 itself, which makes Dart default to returning null. You have to either return the future itself:

Future<String> _f1() {
  return Future.delayed(Duration(seconds: 3)).then((f) {
    return "test";
  });
}

or you need to switch to async/await syntax (my personal recommendation):

Future<String> _f1() async {
  await Future.delayed(Duration(seconds: 3));
  return 'test';
}
Sign up to request clarification or add additional context in comments.

Comments

1

To execute a function you need to add brackets ( arguments ) after its name. It doesn't matter function is a variable or predefined one (constant).

Please check out this examples:

Example 1.

Future<int> add(int a, int b) async {
  return Future.delayed(Duration(seconds: 2)).then((f) {
    return a + b;
  });
}

Future<int> test(Future<int> Function(int a, int b) func) async {
  return await func(3, 2);
}

void main() {
  test(add)
    .then(print); /// will return result of 3+2 after 2 seconds
}

Run this code

Example 2.

String Function(String, String) mergeFunction = (String a, String b) {
  return a + b;
};

void main() {
  print(mergeFunction('Hello ', 'world'));
}

Run this code

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.