Flutter: ButtonStyle()和.styleFrom()有什么区别?

21

我是Flutter的新手。

这是我的代码,

针对ElevatedButton,

ElevatedButton(
                  onPressed: () {
                    // Add your onPressed code here!
                  },
                  child: Text("Login"),
                  style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all<Color>(
                          AppColors.SecondaryColor),
                      foregroundColor: MaterialStateProperty.all<Color>(
                          AppColors.PrimaryColor))),

对于OutlinedButton,

OutlinedButton(
                  onPressed: () {
                    // Add your onPressed code here!
                  },
                  child: Text("Register Now"),
                  style: OutlinedButton.styleFrom(
                    side: BorderSide(width: 2, color: AppColors.SecondaryColor),
                  ))
我的问题是为什么我必须在 OutlinedButton 中使用 styleFrom,而不能使用 ButtonStyle?如果将 OutlinedButton.styleFrom 替换为 ButtonStyle,会出现错误。为什么?
我对 ButtonStylestyleFrom 的使用感到非常困惑。因为互联网上的一些示例使用 ButtonStyle,而另一些则使用 styleFrom
2个回答

11
  1. 你遇到了什么错误?

    正如文档所述,ElevatedButtonOutlinedButton都支持ButtonStyle()和.styleFrom()。

    使用ButtonStyle()时,您需要定义所有必需的属性;而使用ButtonStyle.styleFrom()则选择默认设置值,您只需要更改必需的值。

    如果您告诉我们在使用ButtonStyle()时在OutlinedButton中遇到了什么错误,我们将更容易地帮助您。

---------------------------------------------------------------------------------------------------------------------- 更新的答案

是的,因为ButtonStyle()中的side参数需要MaterialStateProperty类型的值,而不是BorderSide类型的值。请使用以下代码查看其工作原理:

OutlinedButton(
              onPressed: null,
              child: Text('Outlined Button'),
              style: ButtonStyle(
                side: MaterialStateProperty.all(
                  BorderSide.lerp(
                      BorderSide(
                        style: BorderStyle.solid,
                        color: Color(0xffe4e978),
                        width: 10.0,
                      ),
                      BorderSide(
                        style: BorderStyle.solid,
                        color: Color(0xffe4e978),
                        width: 10.0,
                      ),
                      10.0),
                ),
              ),
            ),

输出:在此输入图片描述

查看此链接以了解更多信息。


错误是这样的:“参数类型'BorderSide'无法分配给参数类型'MaterialStateProperty<BorderSide>'。” - Safiah Nadiah
我明白了,非常感谢。 - Safiah Nadiah

5
根据文档所述,styleFrom() 方法是应用按钮样式的简化方式:

它是一种静态方便方法,根据简单值构造一个凸起按钮[ButtonStyle]。

使用所有三个新 Material 按钮(TextButtonOutlinedButtonElevatedButton)会产生相同的行为。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接