【问题标题】:What is the proper way of using ThemeData copyWith in flutter MaterialApp widget?在 Flutter MaterialApp 小部件中使用 ThemeData copyWith 的正确方法是什么?
【发布时间】:2020-05-20 07:31:15
【问题描述】:

我在复制ThemeData.light() 后尝试更改accentColor,然后我有这个带有FloatingActionButton 的示例屏幕

class Sample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        child: Icon(Icons.add),
      ),
     )}}

然后在main.dart 的主窗口小部件中调用runApp,如果我像这样为MaterialApp 窗口小部件设置ThemeDataFloatingActionButton 将具有橙色。

theme: ThemeData(
  accentColor: Colors.orange
)

但如果我尝试从Themedata.light().copyWith 继承颜色,FloatingActionButton 仍将具有来自浅色主题的蓝色。

theme: ThemeData.light().copyWith(
  accentColor: Colors.orange
)

我原以为FloatingActionButton 应该是橙色,因为它继承了light 主题并覆盖了accentColor

【问题讨论】:

    标签: flutter dart material-design flutter-layout


    【解决方案1】:

    这是 Flutter 中的常见问题,但您现在可以通过以下方式解决:

    theme: ThemeData.light().copyWith(
        floatingActionButtonTheme:
            ThemeData.light().floatingActionButtonTheme.copyWith(
                  backgroundColor: Colors.orange,
                ),
      ),
    

    如果您使用任何其他按钮,您应该执行相同操作并覆盖它的主题,

    你可以在这里Updating the Material Buttons and their Themes阅读更多关于这个问题的信息

    buttonColor not honored when using ThemeData.light().copyWith()

    【讨论】:

      【解决方案2】:

      看, 我不认为你可以使用 ThemeData.copyWith() 继承强调色,但如果你确定使用 ThemeData.copyWith() 来更改你的 floatingActionButton 颜色,那么你可以通过以下方式做到这一点,

      theme:ThemeData.dark().copyWith(
          textTheme:ThemeData.dark().textTheme.copyWith(
              title :TextStyle( --your color and text configuratons here like color,font etc)
              button: TextStyle(--do--),
              ...and so on....
          )
      )
      

      您希望在默认文本标题中的配置将进入上述标题属性的 TextStyle 中,按钮也是如此

      现在你可以使用这个在你的 FAB 中实现这个,

      color: Theme.of(context).textTheme.button.color,
      

      通过这样做,您可以获得为 ThemeData 中的按钮设置的颜色。

      如果你强制获取默认的强调色,那么你必须使用

      theme:ThemeData(
          primaryColor: -----
          accentColor : -----
      )
      

      这将允许您使用 FAB 的默认强调色

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-03
        • 2018-08-25
        • 1970-01-01
        • 2021-07-29
        • 1970-01-01
        • 2020-08-18
        相关资源
        最近更新 更多