Imagine you wanted to implement a CustomButton to reuse it across your entire app. In that case, it typically makes sense for it to return a callback function and handle the event where the button is being used. To do so, you pass an onPressed function to the button, which will be invoked by the button's internal onPressed function.
class CustomButton extends StatelessWidget {
const CustomButton({
required this.onPressed,
required this.title,
});
final void Function() onPressed;
final String title;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: Text(title),
);
}
}
Using it:
CustomButton(
onPressed: () => Navigator.pushNamed(context, '/pageTwo'),
title: 'Navigate',
)
The CustomButton can now push, pop, or do all kinds of things. It is way more flexible than if you implemented a button without a callback function:
class ForwardButton extends StatelessWidget {
const ForwardButton({
required this.destination,
required this.title,
});
final String destination;
final String title;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () => Navigator.pushNamed(context, destination),
child: Text(title),
);
}
}
ForwardButton(
destination: '/pageTwo',
title: 'Navigate',
)
If you wanted the ForwardButton to do things other than Navigator.pushNamed, you'd need to add more logic or arguments to the constructor, and it'll quickly become messy.