Flutter - abstract onPressed callback in a widget
1 min read

Flutter - abstract onPressed callback in a widget

Widgets like TextButton offers onPressed callback which is invoked when the user presses it. When we abstract those widgets, what will be the type of function that we need to pass down? Its type should be a function that takes no arguments and returns no data. Flutter provides VoidCallback for this purpose.

class ProfileMenu extends StatelessWidget {
  final String name;
  final Icon icon;
  final VoidCallback onPressed;
  const ProfileMenu({
    Key? key,
    required this.name,
    required this.icon,
    required this.onPressed,
  }) : super(key: key);

  Widget build(BuildContext context) {
    return TextButton(
        style: ButtonStyle(
                MaterialStateProperty.all(Color.fromARGB(255, 226, 223, 223))),
        onPressed: onPressed,
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            children: [
                width: 10,
                  child: Text(
                style: Theme.of(context)
                    ?.copyWith(color: Colors.black54, fontSize: 20),

It is implemented through typedef.

typedef VoidCallback = void Function();