gpt4 book ai didi

android - Flutter - 在 ThemeData 中使用自定义颜色和主题

转载 作者:行者123 更新时间:2023-12-01 17:46:14 39 4
gpt4 key购买 nike

我想在 ThemeData 中使用自定义颜色和主题。我知道我可以在单独的文件中定义它们并导入该文件并使用它们。但我希望这些颜色在更改深色和浅色主题时起作用。
目前,我有单独的深色和浅色主题可以切换。无论如何要分别在深色和浅色 ThemeData 中定义自定义颜色吗?

AppTheme.dart:

class AppTheme {
AppTheme._();

// Light Theme
static final ThemeData lightTheme = ThemeData.light().copyWith(
appBarTheme: AppBarTheme(
color: Colors.grey[100],
brightness: Brightness.light,
),
scaffoldBackgroundColor: Colors.white,

actionButtonColor: Colors.black, // Like this
);

// Dark Theme
static final ThemeData darkTheme = ThemeData.dark().copyWith(
appBarTheme: AppBarTheme(
color: Colors.grey[850],
brightness: Brightness.dark,
),
scaffoldBackgroundColor: Colors.grey[900],

actionButtonColor: Colors.red, // Like this
);
}

应用程序.dart
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Dashboard(),
theme: AppTheme.lightTheme,
darkTheme: AppTheme.darkTheme,
debugShowCheckedModeBanner: false,
);
}
}

最佳答案

我认为您在自己的问题中已经有了答案,您在代码示例中所做的事情是正确的,并且是合法的。当然,“合法”一词是指代码将按预期工作并产生结果,当然,actionButtonColor 部分除外。属性,因为该属性不属于 ThemeData api。

或者,如果您询问如何使用该自定义 actionButtonColor你的主题数据中的属性,你不能。因为它是与 Material 主题一起使用的预定义小部件。那actionButton应该只使用主题中的现有属性。但是如果你真的需要这样做,你可以使用 dart 2.7 中的实验性扩展方法,比如,

extension MyColorScheme on ColorScheme {
Color get actionButtonColor => const Colors.red;
}

ActionButtonComponent(
color: Theme.of(context).colorScheme.actionButtonColor,
);

但是,您将无法为另一个 ThemeData 设置不同的配色方案。与扩展方法一起使用时,例如深色和浅色主题。您可能想查看 this issue .

我希望它有所帮助。

关于android - Flutter - 在 ThemeData 中使用自定义颜色和主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60693179/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com