Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a function with parameters to a VoidCallback

Tags:

flutter

dart

Is it possible to pass a Function with parameters to a VoidCallback?

for example something like this:

class MyClass {   void doSomething(int i){    }    MyOtherClass myOtherClass = new MyOtherClass(doSomething); }   class MyOtherClass {   final VoidCallback callback(int);    MyOtherClass(this.callback);    callback(5); } 
like image 883
Tobias Gubo Avatar asked Apr 29 '18 10:04

Tobias Gubo


People also ask

Why do we pass functions to widgets?

Your answer Functions are first-class objects in Dart and can be passed as parameters to other functions. We pass a function to a widget essentially saying, invoke this function when something happens. Callbacks using interfaces like Android have too much boilerplate code for a simple callback.

Can function be passed as parameter to another function?

Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions. In the example below, a function greet is created which takes a function as an argument.


1 Answers

The declaration of VoidCallback is

typedef void VoidCallback(); 

That is the type of functions that can be called with zero arguments and which does not return a useful value. That does not seem to be what you want. It's not entirely clear what you do want since the program isn't syntactically valid, but would this work for you:

class MyClass {    static doSomething(int i) { /* ... */ }   MyOtherClass myOtherClass = new MyOtherClass(doSomething); } class MyOtherClass {   final void Function(int) callback;   MyOtherClass(this.callback);   void callCallaback() { callback(5); } } 

Here we define the type of the callback field to be the type of functions that can be called with one integer argument and which returns no useful value. The doSomething method has that type, so it can be assigned to callback.

You could also use a typedef to name the function:

typedef Int2VoidFunc = void Function(int); // or: typedef void Int2VoidFunc(int arg); class MyOtherClass {   final Int2VoidFunc callback;   MyOtherClass(this.callback);   void callCallaback() { callback(5); } } 

The effect is exactly the same, it just allows you to use a shorter name for the function type, but that only really makes sense if you use it a lot.

like image 165
lrn Avatar answered Oct 30 '22 05:10

lrn