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

Saf*_*iah 12 flutter flutter-widget

我是 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))),
Run Code Online (Sandbox Code Playgroud)

对于轮廓按钮,

OutlinedButton(
                  onPressed: () {
                    // Add your onPressed code here!
                  },
                  child: Text("Register Now"),
                  style: OutlinedButton.styleFrom(
                    side: BorderSide(width: 2, color: AppColors.SecondaryColor),
                  ))
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么我必须对OutlinedButton使用styleFrom而不是ButtonStyle?如果用ButtonStyle替换OutlinedButton.styleFrom,则会出错。为什么?

我对ButtonStylestyleFrom的使用感到非常困惑。因为互联网上的一些示例使用ButtonStyle而一些使用styleFrom

Uma*_*ala 9

  1. 你得到什么错误?

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

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

    如果您知道在 OutlinedButton 中使用 ButtonStyle() 时遇到了什么错误,那么帮助您会容易得多

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

是的,因为 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),
                ),
              ),
            ),
Run Code Online (Sandbox Code Playgroud)

输出:在此处输入图片说明

有关更多信息,请参阅此链接


F P*_*och 5

正如文档所说,该styleFrom()方法是一种更简单的应用方法Button Style

一种静态便捷方法,可在给定简单值的情况下构造提升按钮 [ButtonStyle]。

TextButton所有三个新材质按钮( 、OutlinedButtonElevatedButton)都有相同的行为