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

  @override
  Widget build(BuildContext context) {
    return TextButton(
        style: ButtonStyle(
            backgroundColor:
                MaterialStateProperty.all(Color.fromARGB(255, 226, 223, 223))),
        onPressed: onPressed,
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            children: [
              icon,
              SizedBox(
                width: 10,
              ),
              Expanded(
                  child: Text(
                name,
                style: Theme.of(context)
                    .textTheme
                    .bodyMedium
                    ?.copyWith(color: Colors.black54, fontSize: 20),
              )),
              Icon(Icons.arrow_right),
            ],
          ),
        ));
  }
}

It is implemented through typedef.

typedef VoidCallback = void Function();