简体   繁体   English

如何更改 ElevatedButton 的禁用颜色

[英]How to I change the disabled color of an ElevatedButton

I am using Flutter ElevatedButton, which is recommended over RaisedButton in the docs.我正在使用 Flutter ElevatedButton,在文档中建议使用 RaisedButton。

In raised button, you could specify and disabledColor.在凸起的按钮中,您可以指定和禁用颜色。 In ElevatedButton, I can not.在 ElevatedButton 中,我不能。

How can I stylize what the ElevatedButton looks like when it is disabled?当 ElevatedButton 被禁用时,我如何设计它的样式?

You can copy paste run full code below您可以在下面复制粘贴运行完整代码
You can use ButtonStyle and check states.contains(MaterialState.disabled) return color you need您可以使用ButtonStyle并检查states.contains(MaterialState.disabled)返回您需要的颜色
In demo code, disabled color is green在演示代码中,禁用颜色为绿色
code snippet代码片段

    ElevatedButton(
      onPressed: null,
      child: Text('Submit disable'),
      style: ButtonStyle(
        backgroundColor: MaterialStateProperty.resolveWith<Color>(
          (Set<MaterialState> states) {
            if (states.contains(MaterialState.pressed))
              return Theme.of(context)
                  .colorScheme
                  .primary
                  .withOpacity(0.5);
            else if (states.contains(MaterialState.disabled))
              return Colors.green;
            return null; // Use the component's default.
          },
        ),
      ),
    ),

working demo工作演示

在此处输入图片说明

full code完整代码

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: null,
              child: Text('Submit disable'),
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.resolveWith<Color>(
                  (Set<MaterialState> states) {
                    if (states.contains(MaterialState.pressed))
                      return Theme.of(context)
                          .colorScheme
                          .primary
                          .withOpacity(0.5);
                    else if (states.contains(MaterialState.disabled))
                      return Colors.green;
                    return null; // Use the component's default.
                  },
                ),
              ),
            ),
            ElevatedButton(
              onPressed: () {
                print("clicked");
              },
              child: Text('Submit enable'),
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.resolveWith<Color>(
                  (Set<MaterialState> states) {
                    if (states.contains(MaterialState.pressed))
                      return Theme.of(context)
                          .colorScheme
                          .primary
                          .withOpacity(0.5);
                    else if (states.contains(MaterialState.disabled))
                      return Colors.green;
                    return null; // Use the component's default./ Use the component's default.
                  },
                ),
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

A simple solution would be to use onSurface property:一个简单的解决方案是使用onSurface属性:

ElevatedButton(
  onPressed: null,
  style: ElevatedButton.styleFrom(
    onSurface: Colors.brown,
  ),
  child: Text('Button'),
)

I created some code to handle disabledText and disabledColor for both FlatButton and RaisedButton with the new TextButton and ElevatedButton widgets.我使用新的 TextButton 和 ElevatedButton 小部件创建了一些代码来处理 FlatButton 和 RaisedButton 的 disabledText 和 disabledColor 。

This gist is here (I couldn't get dartpad to recognize the gist... but you can copy and paste it there directly and it works... it just won't link) https://gist.github.com/wterrill/7942b4bf5d74a8b2ace952ebf213fe5d这个要点在这里(我无法让 dartpad 识别要点......但是你可以直接将它复制并粘贴到那里并且它可以工作......它只是不会链接) https://gist.github.com/ wterrill/7942b4bf5d74a8b2ace952ebf213fe5d

And here's the code itself if you want to copy and paste from here:如果你想从这里复制和粘贴,这里是代码本身:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final bool disableButton = true; // <-- Change this to see buttons disabled
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              FlatButton(
                  child: Text("FlatButton"),
                  onPressed: disableButton
                      ? null
                      : () {
                          print("FlatButton normal");
                        },
                  color: Colors.green,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(
                        Radius.circular(50),
                      ),
                      side: BorderSide(color: Colors.purple, width: 3.0)),
                  disabledColor: Colors.grey,
                  disabledTextColor: Colors.pink),
              SizedBox(height: 25),
              FlatButtonX(
                  childx: Text("TextButton"),
                  onPressedx: disableButton
                      ? null
                      : () {
                          print("FlatButtonX (TextButton)");
                        },
                  colorx: Colors.green,
                  textColorx: Colors.black,
                  shapex: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(
                        Radius.circular(50),
                      ),
                      side: BorderSide(color: Colors.purple, width: 3.0)),
                  disabledColorx: Colors.grey,
                  disabledTextColorx: Colors.pink),
              SizedBox(height: 100),
              RaisedButton(
                child: Text('RaisedButton'),
                color: Colors.green,
                textColor: Colors.black,
                onPressed: disableButton
                      ? null
                      : () {
                          print("RaisedButton normal");
                        },
                shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(
                        Radius.circular(50),
                      ),
                      side: BorderSide(color: Colors.purple, width: 3.0)),
                disabledColor: Colors.grey,
                  disabledTextColor: Colors.pink,
              ),
              SizedBox(height: 25),
              RaisedButtonX(
                childx: Text('ElevatedButton'),
                colorx: Colors.green,
                textColorx: Colors.black,
                onPressedx:disableButton
                      ? null
                      : () {
                          print("RaisedButtonX (ElevatedButton)");
                        },
                shapex: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(
                        Radius.circular(50),
                      ),
                      side: BorderSide(color: Colors.purple, width: 3.0)),
                                  disabledColorx: Colors.grey,
                  disabledTextColorx: Colors.pink,
              )
            ],
          ),
        ),
      ),
    );
  }
}

Widget FlatButtonX(
    {Color colorx,
    @required Widget childx,
    RoundedRectangleBorder shapex,
    @required Function onPressedx,
    Key keyx,
    Color disabledColorx,
    Color disabledTextColorx,
    Color textColorx}) {
  if (disabledTextColorx == null && textColorx == null) {
    disabledTextColorx = colorx;
  }
  if (textColorx == null) {
    textColorx = colorx;
  }
  return TextButton(
      key: keyx,
      style: ButtonStyle(
        foregroundColor: MaterialStateProperty.resolveWith<Color>(
          // text color
          (Set<MaterialState> states) => states.contains(MaterialState.disabled)
              ? disabledTextColorx
              : textColorx,
        ),
        backgroundColor: MaterialStateProperty.resolveWith<Color>(
          // background color    this is color:
          (Set<MaterialState> states) =>
              states.contains(MaterialState.disabled) ? disabledColorx : colorx,
        ),
        shape: MaterialStateProperty.all(shapex),
      ),
      onPressed: onPressedx as void Function(),
      child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 8.0), child: childx));
}

Widget RaisedButtonX(
    {Color colorx,
    @required Widget childx,
    RoundedRectangleBorder shapex,
    @required Function onPressedx,
    Key keyx,
    Color disabledColorx,
    Color disabledTextColorx,
    Color textColorx}) {
  if (disabledTextColorx == null && textColorx == null) {
    disabledTextColorx = colorx;
  }
  if (textColorx == null) {
    textColorx = colorx;
  }
  return ElevatedButton(
      key: keyx,
      style: ButtonStyle(
        foregroundColor: MaterialStateProperty.resolveWith<Color>(
          // text color
          (Set<MaterialState> states) => states.contains(MaterialState.disabled)
              ? disabledTextColorx
              : textColorx,
        ),
        backgroundColor: MaterialStateProperty.resolveWith<Color>(
          // background color    this is color:
          (Set<MaterialState> states) =>
              states.contains(MaterialState.disabled) ? disabledColorx : colorx,
        ),
        shape: MaterialStateProperty.all(shapex),
      ),
      onPressed: onPressedx as void Function(),
      child: childx);
}

use onSurface in ElevatedButton.styleFrom在 ElevatedButton.styleFrom 中使用 onSurface

 ElevatedButton(
          style: ElevatedButton.styleFrom(
                   primary: Colors.white,
                   onSurface: Colors.green,
          ),
          child: Text("next"),
          onPressed:null
 )

Because the original disabled color has opacity you can simply wrap it in a container and give the container the color you want.因为原始禁用的颜色具有不透明度,您可以简单地将其包装在容器中并为容器提供您想要的颜色。 It's a bit hacky but it works and is fast done.这有点hacky,但它可以工作并且很快就完成了。 Especialy if you have many buttons with different colors.特别是如果您有许多具有不同 colors 的按钮。

The cleanest way would be a custom button widget where you can handover the parameters you need.最简洁的方法是自定义按钮小部件,您可以在其中移交所需的参数。

Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(const Radius.circular(radius)),
          color: containerColor,
        ),
        width: containerWidth,
        height: containerHeight,
        child: ElevatedButton(
          onPressed: bool ? onPressed : null,
          child: Text(
            buttonText,
          ),
        ),
      ),

Make all variables nullable which are not allways needed.使并非总是需要的所有变量都可以为空。

Try This:尝试这个:

style: ElevatedButton.styleFrom(
                  disabledBackgroundColor:
                      Theme.of(context).primaryColor.withOpacity(.8), // Background Color
                  disabledForegroundColor: Colors.white70, //Text Color
                ),

Use button's style property.使用按钮的style属性。 It contains backgroundColor of MaterialStateProperty<Color> .它包含MaterialStateProperty<Color> backgroundColor There is a constant MaterialState.disabled .有一个常量MaterialState.disabled I think this is what you need.我认为这就是你所需要的。 https://api.flutter.dev/flutter/material/MaterialStateProperty-class.html https://api.flutter.dev/flutter/material/MaterialStateProperty-class.html

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

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