You can create a custom button widget in Flutter by extending the StatelessWidget
class and defining a build
method that returns a custom button.
Steps to Create a Custom Button Widget
-
Create a new class that extends StatelessWidget:
class CustomButton extends StatelessWidget { // ... }
-
Define the constructor to accept required parameters:
class CustomButton extends StatelessWidget { final String text; final VoidCallback onPressed; final Color backgroundColor; final Color textColor; CustomButton({ required this.text, required this.onPressed, this.backgroundColor = Colors.blue, this.textColor = Colors.white, }); // ... }
-
Implement the build method:
@override Widget build(BuildContext context) { return ElevatedButton( onPressed: onPressed, style: ElevatedButton.styleFrom( backgroundColor: backgroundColor, foregroundColor: textColor, ), child: Text(text), ); }
Example Usage
CustomButton(
text: 'Click me',
onPressed: () {
// Perform action on button click
},
backgroundColor: Colors.green,
textColor: Colors.black,
),
Customization Options
You can customize your button further by:
- Adding a border: Use
OutlinedButton
instead ofElevatedButton
and set theborderSide
property. - Adding icons: Use
Icon
widget within thechild
property. - Changing the shape: Use the
shape
property and set a customRoundedRectangleBorder
orStadiumBorder
. - Adding padding and margin: Use the
padding
andmargin
properties to control spacing around the button.
Benefits of Using Custom Buttons
- Consistency: Ensure a consistent look and feel across your app.
- Branding: Create buttons that align with your brand identity.
- Flexibility: Easily adjust button styles based on context or user preferences.
- Reusability: Use the same button widget throughout your app, reducing code duplication.