Search code examples
flutterdartbuttonflutter-layout

Create a button with an image in Flutter?


How do you create a button with an image using Flutter? It seems like the simplest thing to do, but the image does not fill the parent widget completely. This is what I have:

Container(child: ConstrainedBox(
    constraints: BoxConstraints.expand(),
    child: FlatButton(onPressed: null,
        child: Image.asset('path/the_image.png'))))

I followed this post as guidance. My image looks like this:

enter image description here

Notice the padding around the PNG image - it's not in the code. Where does it come from? The PNG itself does not have canvas padding, so this must not be the correct technique.

All I need is a button with an image that fills the entire FlatButton, or another widget I can add actions to, without distorting the image.


Solution

  • Having an image inside a FlatButton might not fit your requirements, as it takes care of some styling ( like that padding ) on its own.

    To have full control on your button aspect you might want to build a custom widget ( even a simple Container with a custom BoxDecoration to display the image ) and wrap it with a gesture recognizer to handle user interactions ( a simple tap, in your case ). The simplest implementation would use a GestureDetector, but there are also other widgets, like InkWell that renders a material design ripple over the tappable widget surface on tap.