Home > Mobile >  Dart assign a function/method to variable after declaration
Dart assign a function/method to variable after declaration

Time:12-24

I want to assign a function, with parameters, to an already declared variable, So I be able to execute it later.

Something like that:

void main() {
  Function p;
  p = print('1'); // should not execute;
  p;
}

How do I do that? Is it possible?

CodePudding user response:

You can do it like

void main() {
  late Function p;
  p = () {
    print('1');
  };
  p(); // it will print 1
}

CodePudding user response:

 void Function(Object? object) p;
 p = print; 
 p.call('1');

CodePudding user response:

For the example you have provided you can do this:

void main() {
  Function p = (){print('1');};
}

now you can call p() to execute it later.

  • Related