How to Change the Color of ElevatedButton in Flutter

The ElevatedButton is the ready to go button for flutter. I already have a blog post on adding ElevatedButton in flutter. Now, let’s check how to change the color of the elevated button in flutter.

By default, the elevated button inherits a blue color. We can tweak the default style using the style parameter and ButtonStyle class. See the following snippet.

ElevatedButton(
  style: ButtonStyle(
    backgroundColor: MaterialStateProperty.resolveWith<Color>(
      (Set<MaterialState> states) {
        if (states.contains(MaterialState.pressed))
          return Colors.green;
        return null; // Use the component's default.
      },
    ),
  ),
)

Button has different states such as pressed, disabled, hovered etc. You can change the style for each state. In the above snippet, the default color of the button changes to green when it is pressed.

If you just want to change the background color and foreground color irrespective of the states then you can do as given below.

ElevatedButton(
  style: ElevatedButton.styleFrom(
    primary: Colors.red, // background
    onPrimary: Colors.white, // foreground
  ),
  onPressed: () { },
  child: Text('ElevatedButton with custom foreground/background'),
)

In the following flutter elevated button example, I am giving a red background color irrespective of all the button states.


import 'package:flutter/material.dart';
void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter ElevatedButton Background Color Example',
      home: FlutterExample(),
    );
  }
}

class FlutterExample extends StatelessWidget {
  FlutterExample({Key key}) : super(key: key);


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
          child: Padding(
            padding: EdgeInsets.all(30),
            child:ElevatedButton(onPressed: () {},
                  style: ButtonStyle(backgroundColor: MaterialStateProperty.all<Color>(Colors.red) ),
                  child: Text(' Elevated Button'))),));
}

}

Following is the output of this flutter tutorial.

elevated button background color example

This is how you can change the background color of the elevated button in flutter.

Leave a Comment

Your email address will not be published. Required fields are marked *