Skip to main content

Pass a Method as A Parameter to A Widget in Flutter

When creating a custom widget, we need to allow a robust way of handling onTap or any similar event. That’s why we need to pass a function to a custom widget’s class.

In Flutter, you can easily pass a method as a parameter to a widget. This lets you customize the behavior of the widget without having to create a new one. In this post, we’ll show you how to do it.

We will use VoidCallBack typedef which is a signature of callbacks that have no arguments. This typedef won’t return any data as well.

class ListCard extends StatefulWidget {
  final List<Widget>? children;
  final VoidCallback? onTap;
  final Color? cardColor;
  const ListCard({Key? key, this.children, this.onTap, this.cardColor}) : super(key: key);

  State<ListCard> createState() => _ListCardState();

class _ListCardState extends State<ListCard> {
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(bottom: MyTheme.paddingTop),
      child: RippleEffect(
        onTap: widget.onTap,
        child: Container(
          padding: const EdgeInsets.all(MyTheme.padding),
          decoration: BoxDecoration(
            color: widget.cardColor ?? MyTheme.cardColor,
              border: Border.all(
                color: widget.cardColor ?? MyTheme.cardColor,
              borderRadius: MyTheme.radius),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: widget.children!,


By continuing to use the site, you agree to the use of cookies.