Backgrounded Flutter Buttons
How to create beautiful and simple backgrounded buttons on Flutter
When I moved from React Native to Flutter, one of the first issues I had was how to create customized buttons, such as one with a background color. And soon I’ve realized that I wasn’t alone on that, because I found many other coders struggling with the same, and the documentation didn’t help too much.
The problem is how can you add a background to a button? I mean add a gradient, an image and whatever you want. The first thing I’ve tested was try to add a color to the background of a button. Looking at documentation I found there’s no suitable constructor to do so.
Thus, an approach I thought might work was wrap the button inside a kind of “view”, in a very React’s dialect, or, in Flutter terms, a Widget Container and change its background. So let’s do it a simple example to see how it works.
First step, create the Flutter app project:
flutter create background_button
Second, clean the main.dart file and add the following snippet:
Create inside the lib folder a directory called src and add a file called app.dart with a snippet below:
Create inside the src folder a diretory called component and add a file called background_button.dart with a snippet below:
And the result is:
As you can see the ‘Click Me’ button doesn’t have any background and due that it gets the background color of the container. In order to setup a background color follow these steps:
- Create a Container to your FlatButton;
- Add a decoration to your Container, here I’m using a BoxDecoration;
- Add a gradient to your decoration, here I’m using a LinearGradient;
- Add an array of colors to your gradient, and setup your gradient behavior;
And the final code is the following:
And the result is:
Okay, it’s done! But as this problem might back in many other situations would be useful create a reusable code to wrap those steps and just reuse whenever you need. So let’s create a directory called reusable inside the src folder and add a file called util_button.dart with a snippet below:
And refactoring the BackgroundButton class:
Summarizing
So far we’ve seen how to create a button with a customized background, and that solution not only works for gradients, but also for images and any other backgrounds you might need.
That’s it! Till next.