Max888
Max888

Reputation: 3770

Dart function variable/field type declaration

I want to have a function as a class field like below (for use as a callback), but would like to specify what argument types the function is aloud and what it returns, e.g. it accept a String called mystring and returns a Future<int>, so the type might look like (pseudocode): Function(String mystring -> Future<int>) or something. I haven't been able to find anything like this in the docs, is something similar possible in Dart? Also I am not sure what the terminology for something like this is which makes it harder to search for.

class Test {
  Function myfunc;
  Test(this.myfunc) {}
}

Upvotes: 0

Views: 72

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 17143

Yes, you can do this. The syntax is to place the return type before Function and put the parameters in parentheses:

class Test {
  Future<int> Function(String) myfunc;
  Test(this.myfunc);
}

You could also use a typedef:

typedef FunctionType = Future<int> Function(String);


class Test {
  FunctionType myfunc;
  Test(this.myfunc);
}

Upvotes: 1

Related Questions