A2oz

How do I create a custom button widget in Flutter?

Published in Flutter UI Widgets 2 mins read

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

  1. Create a new class that extends StatelessWidget:

    class CustomButton extends StatelessWidget {
      // ...
    }
  2. 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,
      });
    
      // ...
    }
  3. 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 of ElevatedButton and set the borderSide property.
  • Adding icons: Use Icon widget within the child property.
  • Changing the shape: Use the shape property and set a custom RoundedRectangleBorder or StadiumBorder.
  • Adding padding and margin: Use the padding and margin 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.

Related Articles