Home > front end >  How can I change the disabled button color in Flutter?
How can I change the disabled button color in Flutter?

Time:01-21

I'm trying to create a theme for an app that has white buttons with black text but when I disable a button, it is almost indistinguishable from an enabled button. I want the disabled button to have a dark gray background and a light gray text to make it look like it's actually disabled. How can I achieve this in a Theme level instead of changing the widget attributes for every button I want to disable? Here's a code that shows 2 buttons with the properties of the buttons set by the app's Theme:

import 'package:flutter/material.dart';

void main() {
  runApp(const Home());
}

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

  static final ThemeData _theme = ThemeData.from(
    colorScheme: ColorScheme.fromSwatch(
      primarySwatch: Colors.green,
      backgroundColor: Colors.blue,
    ),
  ).copyWith(
    elevatedButtonTheme: ElevatedButtonThemeData(
      style: ButtonStyle(
        foregroundColor: MaterialStateProperty.all(Colors.black),
        backgroundColor: MaterialStateProperty.all(Colors.white),
      ),
    ),
  );

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: _theme,
      home: Scaffold(
        body: SafeArea(
          child: Column(
            children: [
              ElevatedButton(
                onPressed: () {},
                child: const Text('Enabled'),
              ),
              ElevatedButton(
                onPressed: null,
                child: const Text('Disabled'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

enter image description here

CodePudding user response:

You can customize the style ef ElevatedButton using the style property, there are a disabledBackgroundColor and disabledForegroundColor that you can control and customize when the button is disabled (onPressed is null) :

 // ...
 style: ElevatedButton.styleFrom(
              disabledBackgroundColor: Colors.grey, // The background Color
              disabledForegroundColor: Colors.yellow, // The text Color
            ),
  • Related