【问题标题】:How to change Flutter ElevatedButton style with if condition?如何使用 if 条件更改 Flutter ElevatedButton 样式?
【发布时间】:2022-10-18 19:57:12
【问题描述】:

如果我想在颤动中创建提升按钮,如果条件为真,则背景为绿色,如果为假,则为蓝色

我可以使用带有提升按钮的 if 条件吗?

【问题讨论】:

  • 风格:是真的吗? buttonStyle 1 : 按钮样式 2

标签: flutter


【解决方案1】:

如果你想使用ButtonStyle

ElevatedButton(
   onPressed: () {},
   child: Text('button'),
   style: ButtonStyle(
        backgroundColor:MaterialStateProperty.all( yourCondetion ? Colors.green : Colors.blue,),
        ),
   ),

如果你想使用ElevatedButton.styleFrom

ElevatedButton(
  onPressed: () {},
  child: Text('button'),
  style: ElevatedButton.styleFrom(
    primary: yourCondetion ? Colors.green : Colors.blue,
  ),
),

【讨论】:

    【解决方案2】:

    使用styleFrom 设置样式高架按钮

          ElevatedButton(
            child: Text('Button'),
            onPressed: () {},
            style: ElevatedButton.styleFrom({
              (condition) ? Colors.green : Colors.red,
            }),
          ),
    

    【讨论】:

      【解决方案3】:

      应该是这样的:

      ElevatedButton(
        child: Text('My Button')
        onPress: () {}
        style: ElevatedButton.styleFrom(
          primary:  isTrue? Colors.green : Colors.blue
      )
      

      【讨论】:

        【解决方案4】:

        您可以创建一个类型为ButtonStyle 的变量。我们经常使用包含每个按钮样式的文件。

        例如:文件button_style.dart

        var btnStyleGreen = ButtonStyle(color: green)
        
        var btnStyleBlue = ButtonStyle(color: blue)
        

        您的工作文件:

        ButtonStyle yourBtnStyle;
        if (isBlue) yourBtnStyle = btnStyleGreen; else yourBtnStyle = btnStyleGreen;
        
        ElevatedButton(
          child: Text('Button'),
          onPress: () {},
          style: yourBtnStyle,
        )
        

        大型产品通常就是这样。

        【讨论】:

          【解决方案5】:
          ElevatedButton(
             onPressed: () {},
             child: Text('button'),
             style: ButtonStyle(
                  backgroundColor:MaterialStateProperty.all( yourCondetion ? Colors.green : Colors.blue,),
                  ),
             )
          

          【讨论】:

          • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
          猜你喜欢
          • 1970-01-01
          • 2015-04-03
          • 2021-06-21
          • 1970-01-01
          • 2021-03-07
          • 1970-01-01
          • 2021-06-08
          • 1970-01-01
          • 2013-08-27
          相关资源
          最近更新 更多