Home > Back-end >  How do I create a custom widget that takes a function as parameter and uses it?(flutter)
How do I create a custom widget that takes a function as parameter and uses it?(flutter)

Time:06-22

ElevatedButton customBTN(String test, Icon icon, Colors color, double height, double width, passedfunc,)

  return ElevatedButton(
    style: ElevatedButton.styleFrom(),
    child: Text('a'),
    onPressed: **passedfunc**,
  );

CodePudding user response:

You can use VoidCallback or Function as widget variable,

class MyW extends StatelessWidget {
  final VoidCallback? callback;
  const MyW({Key? key, this.callback}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(),
      child: Text('a'),
      onPressed: callback,
    );
  }
}

And whenever you use this widget you will get a callback function

MyW(
  callback: () {},
),

You can choose function or typedef for passing data.

class MyW extends StatelessWidget {
  final Function(int data) myFunc;
  final VoidCallback? callback;
  const MyW({
    Key? key,
    required this.myFunc,
    this.callback,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(),
      child: Text('a'),
      onPressed: () {
        myFunc(1);
        if (callback != null) callback!();
      },
    );
  }
}

And use case

MyW(
  callback: () {},
  myFunc: (data) {},
),

If you are using StatefulWidget call method using widget.YourFunction

Possible duplicate and more about passing function

CodePudding user response:

class MyCustomWidget extends StatelessWidget {
  final Function onPress;
  const MyCustomWidget({Key? key, this.onPress}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(),
      child: Text('a'),
      onPressed: onPress.call, // or onPressed: () => onPress.call(),
    );
  }
}
  • Related