Change Elevated Button Color on Press in Flutter

I already have published few blog posts on the ElevatedButton widget. ElevatedButton is the ready-to-go button for many Flutter developers. In this blog post let’s check how to change the color of the elevated button at the time of pressing.

You can change the background color of the ElevatedButton using MaterialStateProperty class. You can change the color of the button based on the states too. See the code snippet given below.

ElevatedButton(
          child: Text('Elevated Button'),
          onPressed: () {
            print('Pressed');
          },
          style: ButtonStyle(
            backgroundColor: MaterialStateProperty.resolveWith<Color>(
              (Set<MaterialState> states) {
                if (states.contains(MaterialState.pressed)) return Colors.green;
                return Colors.greenAccent;
              },
            ),
          ),
        )

Here, we set green color when the button state is pressed whereas greenAccent color is set for all other button states.

Following is the complete example.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Elevated Button Example',
      debugShowCheckedModeBanner: false,
      home: FlutterExample(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Elevated Button OnPress Color Change')),
        body: Center(
            child: ElevatedButton(
          child: Text('Elevated Button'),
          onPressed: () {
            print('Pressed');
          },
          style: ButtonStyle(
            backgroundColor: MaterialStateProperty.resolveWith<Color>(
              (Set<MaterialState> states) {
                if (states.contains(MaterialState.pressed)) return Colors.green;
                return Colors.greenAccent;
              },
            ),
          ),
        )));
  }
}

And following is the output.

Elevated button onpress color change

That’s how set OnPress background color for elevated button in Flutter.

Leave a Comment

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