无法将参数类型“MaterialColor”分配给参数类型“MaterialStateProperty<Color>

mca*_*gno 2 dart flutter

我有一个与新的 ElevatedButtonThemeData 小部件相关的问题,基本上我想为我的应用程序中的所有 ElevatedButtons 设置背景颜色,我正在努力尝试通过执行以下操作在 ThemeData 定义中设置它:

      theme: ThemeData(
        ...
        elevatedButtonTheme: ElevatedButtonThemeData(
            style: ButtonStyle(backgroundColor: Colors.red)), // Here Im having the error
        ...
        ),
      ),
Run Code Online (Sandbox Code Playgroud)

错误:

参数类型 'MaterialColor' 不能分配给参数类型 'MaterialStateProperty<Color?>?'.dartargument_type_not_assignable)

Ras*_*san 31

下面是一个代码片段,显示了我如何使用材质状态属性设置文本按钮的样式。

您可以看到如何添加different types值:

TextButton(style: ButtonStyle(
      padding: MaterialStateProperty.all(const EdgeInsets.all(0)),
      elevation: MaterialStateProperty.all(8),
      shape: MaterialStateProperty.all(
          RoundedRectangleBorder(borderRadius: BorderRadius.circular(50))),
      backgroundColor: MaterialStateProperty.all(Colors.blue),
      shadowColor: MaterialStateProperty.all(
          Theme.of(context).colorScheme.onSurface),
    ),),
Run Code Online (Sandbox Code Playgroud)

我希望这能给你一个想法。

要了解更多关于MaterialStateProperty的信息,您可以观看这个官方视频: MaterialStateProperties | 解码颤振


Kul*_*pas 12

而不是使用ButtonStyle()尝试:

style: ElevatedButton.styleFrom(backgroundColor: Colors.red)
Run Code Online (Sandbox Code Playgroud)

  • 这是一次性的正确答案。`.styleFrom()` 在 flutter 中很方便! (4认同)

mca*_*gno 8

阅读文档后,我找到了设置颜色的方法。

  theme: ThemeData(
    ...
    elevatedButtonTheme: ElevatedButtonThemeData(
        style: ButtonStyle(backgroundColor: MaterialStateProperty.all<Color>(Colors.red))), // Here Im having the error
    ...
    ),
  ),
Run Code Online (Sandbox Code Playgroud)

  • 这非常有效! (3认同)

Bro*_*Das 8

MaterialStateProperty.all<Color>(Colors.red)
Run Code Online (Sandbox Code Playgroud)

这将返回MaterialStateProperty<Color?>数据类型。