Backgrounded Flutter Buttons

How to create beautiful and simple backgrounded buttons on Flutter

Flavio Farias
umpontoseis
3 min readJul 17, 2018

--

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:

Main function

Create inside the lib folder a directory called src and add a file called app.dart with a snippet below:

BackgroundButton class call via Stateless Widget

Create inside the src folder a diretory called component and add a file called background_button.dart with a snippet below:

The above code just creates a button and places at the center of the screen

And the result is:

The result :)

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:

  1. Create a Container to your FlatButton;
  2. Add a decoration to your Container, here I’m using a BoxDecoration;
  3. Add a gradient to your decoration, here I’m using a LinearGradient;
  4. Add an array of colors to your gradient, and setup your gradient behavior;

And the final code is the following:

The backgrounded button

And the result is:

Done ^^

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:

Reusable Widget

And refactoring the BackgroundButton class:

The refactored backgrounded button

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.

About the project

Contributors: Aurélio Buarque

Full project on GitHub: Background Button

My other pages

Facebook | Instagram | LinkedIn | GitHub

--

--