简体   繁体   English

如何更改 Flutter 中禁用按钮的颜色?

[英]How can I change the disabled button color in Flutter?

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?我怎样才能在Theme级别实现这一点,而不是更改我想要禁用的每个按钮的小部件属性? Here's a code that shows 2 buttons with the properties of the buttons set by the app's Theme :这是显示 2 个按钮的代码,按钮的属性由应用程序的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'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

在此处输入图像描述

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属性自定义样式 ef ElevatedButton ,当按钮被禁用时( onPressed为空),您可以控制和自定义disabledBackgroundColordisabledForegroundColor

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM