Tobias Gubo
Tobias Gubo

Reputation: 3229

Pass a function with parameters to a VoidCallback

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);
}

Upvotes: 139

Views: 227573

Answers (10)

Madhan
Madhan

Reputation: 51

 // We can pass function  like this too....   
class A
{
void showMessage(BuildContext context, String message) {
       ScaffoldMessenger.of(context).showSnackBar(
       SnackBar(
         content: Text(message),
         duration: const Duration(seconds: 2),
         action: SnackBarAction(
         textColor: Colors.blue,
         label: 'OKAY',
         onPressed: () {},
        ),
      ),
   );
}
// calling another class and passing function
EditPage(     
        showMessage: (String message) {
          showMessage(context, message);
        },
      )
}
class EditPage{
final Function showMessage;
 EditPage({required this.showMessage})

}
// we can call by
widget.showMessage(context,'message value');

Upvotes: 1

Dansp
Dansp

Reputation: 1745

Ways that I use:

1 - Declare with typedef:

typedef MyFunction = void Function(int);

class MyClass {
    final MyFunction myFunction;
    
    void onBunttonPressed() {
        //using function
        myFunction(1);
    }
}

2 - Direct in variable:

class MyClass {
    final void Function(int) myFunction;
        
    void onBunttonPressed() {
        //using function
        myFunction(1);
    }
 }

Upvotes: 4

Kalpesh Khandla
Kalpesh Khandla

Reputation: 746

Simple way to do to is create a stateless or stateful widget and pass callback function into it. Consider a code snippet like a below:

import 'package:flutter/material.dart';

class TestFunctionWidget extends StatelessWidget {
final Function onCallback;
 const TestFunctionWidget({
  Key key,
  this.onCallback,
 }) : super(key: key);

@override
Widget build(BuildContext context) {
return GestureDetector(
  onTap: () {
    this.onCallback();
  },
  child: Container(
    child: Text("Test Call Back"),
  ),
);
}
}

Now to use it in a screen consider a code snippet.

import 'package:flutter/material.dart';
import 'package:netflix_clone/pages/test_widget.dart';

class TestScreen extends StatefulWidget {
 TestScreen({
 Key key,
 }) : super(key: key);
 @override
_TestScreen1State createState() => _TestScreen1State();
}
class _TestScreen1State extends State<TestScreen> {
@override
Widget build(BuildContext context) {
return TestFunctionWidget(
  onCallback: () {
    // To do
  },
);
}
}

Upvotes: 7

Jakub S.
Jakub S.

Reputation: 6080

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")},
),

Upvotes: 58

Francisco Varela
Francisco Varela

Reputation: 359

Just replace VoidCallback with Function(int)

class MyClass {
  void doSomething(int i){

  }

  MyOtherClass myOtherClass = new MyOtherClass(doSomething);
}


class MyOtherClass {
 //OP code (does not work): final VoidCallback callback(int); 
 final Function(int) callback;

  MyOtherClass(this.callback);

  callback(5);
}

Upvotes: 20

Anil Kumar
Anil Kumar

Reputation: 1984

1) Create typedef first in any constant class:

typedef StringVoidFunc = void Function(String);

2) Pass from calling function class one

showAlertDialog(doSomething);

3) Call back handle Function

void doSomething(String i){
Navigator.pop(context);
setState(() {

});

}

4) From where you want to fire call back from Class Two

    showAlertDialog(StringVoidFunc callback) {
     callback("delete");
}

Upvotes: 5

CopsOnRoad
CopsOnRoad

Reputation: 268304

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);

Upvotes: 16

Duncan Jones
Duncan Jones

Reputation: 69389

Flutter already has a typedef for this: ValueSetter.

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

Upvotes: 16

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 277567

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);

}

Upvotes: 45

lrn
lrn

Reputation: 71828

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.

Upvotes: 172

Related Questions