Flutter › Custom Widgets & Reusable Components
Why should you extract a repeated piece of widget code into its own custom, reusable widget class rather than duplicating that same code across multiple different screens?
BeginnerAnswer
Duplicating the same widget building code across several different screens means that if a bug is ever discovered or the design needs to change in the future, that same fix or change has to be manually applied and kept consistent across every single duplicated location, whereas extracting that repeated code into its own dedicated custom widget class means it only ever needs to be defined and maintained in exactly one single place, and every screen that uses it automatically benefits from any future fix or improvement immediately.
class PrimaryButton extends StatelessWidget {
final String label;
final VoidCallback onPressed;
const PrimaryButton({super.key, required this.label, required this.onPressed});
@override
Widget build(BuildContext context) {
return ElevatedButton(onPressed: onPressed, child: Text(label));
}
}Real-world example A team notices the exact same styled submit button code is duplicated across five different screens, and extracts it into a single reusable PrimaryButton widget, making a subsequent design update require changing just one file instead of five.