Pass a function with parameters to a VoidCallback

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.


create your own callback instead

typedef void MyCallback(int foo);

class MyClass {
  void doSomething(int i){

  }

  MyOtherClass myOtherClass = new MyOtherClass(doSomething);
}


class MyOtherClass {
  final MyCallback callback;

  MyOtherClass(this.callback);

}

Example in UI case; you may need create widget and pass click function.

Step 1: create widget with function as parameter in constructor:

Container _cardButton({
  Function onClickAction,
}) {
  return Container(
    width: 340,
    height: 90,
    child: InkWell(
      splashColor: Colors.blue.withAlpha(30),
      onTap: () {
        onClickAction();
      },
      child: Card(
        elevation: 5,
        child: somechild,
      ),
    ),
  );

Step 2: implement widget to the three view and pass function like this:

_cardButton(
    onClickAction: () => {debugPrint("CLICKED")},
),

Flutter already has a typedef for this: ValueSetter.

So you can pass an instance of ValueSetter<int> to your other class.


Instead of VoidCallback, you can use ValueChanged<T>, here is an example:

class MyClass {
  static void doSomething(int i) {}

  MyOtherClass myOtherClass = MyOtherClass(doSomething);
}

class MyOtherClass {
  final ValueChanged<int> callback;

  MyOtherClass(this.callback);
}

You can then call callback with any int value

callback(10);