Home > Enterprise >  Function and Function()
Function and Function()

Time:11-16

What is difference between Function and Function() in Dart/Flutter? for example in such a code final Function x; final Function() x;

CodePudding user response:

Function itself represents the type and the Object. You could declare as variable and as parameter in a function. Or use it with your exposed methods.

final Function x = () => print('x');
Function.apply(x, [])

Normally when we use parenthesis in front of a declaration it represents a calling for that function or method. But in this case it only represents the same thing a void function without parameters.

I made some tests and when it is empty Dart just ignores and the execution is the same, but we could put more code and improve the declaration of the type of the function and Dart interprets the code and blocks us to assign functions that have different signatures. Ex: I can`t apply the same anonymous function used in exec on exec2 and vice versa.

As we could see in the code above we could call the execution of a function received as a parameter without concerns about the types declared in signature of the method.

class Foo {
  exec(Function() x) {
    x();
  }

  exec2(Function(String foo) x, String bar) {
    x(bar);
  }
}

void main() {
  final foo = Foo();
  final foo2 = (String bar) => print(bar);
  foo.exec(() => print('as a class function')); // 'as a class function'
  foo.exec2(foo2, 'This could improve a lot my code'); //'This could improve a lot my code'
}

CodePudding user response:

As stated in the Function documentation, it is:

The base class for all function types.

A variable declared with type Function therefore can be assigned any function. However, you won't get any type-safety when invoking it.

Meanwhile a Function() type is a function with an unspecified (i.e., dynamic) return type and that takes zero arguments.

  • Related