3

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?

3 Answers 3

7

You can do it like

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

Thanks Amir, but in my case I have to assign my function after the deceleration
@genericUser You’re welcome, nothing changes actually, you can do it this way: void main() { late Function p; p = () { print('1'); }; p(); }
2
 void Function(Object? object) p;
 p = print; 
 p.call('1');

2 Comments

Hey @Raegtime thanks for replying, I have edited my question. I need to assign my the function after declaring the variable.
void Function(Object? object) p; p = ()=>print('1'); p.call();

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.