You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter的Theme层级修改禁用按钮的颜色?

解决方案

要在Theme层级统一设置按钮的禁用状态样式,你需要使用MaterialStateProperty.resolveWith来根据按钮的状态动态返回对应颜色,而非MaterialStateProperty.all(它会让所有状态共用同一种样式)。

修改主题配置部分,针对按钮的文本色和背景色分别设置状态对应的样式:

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.resolveWith((states) {
          if (states.contains(MaterialState.disabled)) {
            return Colors.grey[300];
          }
          return Colors.black;
        }),
        // 背景颜色:启用时白色,禁用时深灰色
        backgroundColor: MaterialStateProperty.resolveWith((states) {
          if (states.contains(MaterialState.disabled)) {
            return Colors.grey[700];
          }
          return Colors.white;
        }),
      ),
    ),
  );

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: _theme,
      home: Scaffold(
        body: SafeArea(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: ElevatedButton(
                  onPressed: () {},
                  child: const Text('Enabled'),
                ),
              ),
              const SizedBox(height: 16),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: ElevatedButton(
                  onPressed: null,
                  child: const Text('Disabled'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

说明

  • MaterialStateProperty.resolveWith会接收当前按钮的状态集合(如disabled、pressed等),你可以根据是否包含目标状态返回对应样式。
  • 这里针对MaterialState.disabled状态,分别设置了浅灰色文本和深灰色背景,启用状态保留原有的黑文本白背景,两种状态会有明显区分。
  • 额外调整了布局对齐和间距,让按钮显示更规整。

内容的提问来源于stack exchange,提问作者Eddy Todd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 23:05:22