如何在Flutter ThemeData中使用ColorScheme?

8ljdwjyq  于 2022-11-30  发布在  Flutter
关注(0)|答案(1)|浏览(275)

我尝试创建两种配色方案,一种用于亮模式,一种用于暗模式。

return MaterialApp(
  initialRoute: '/',
  routes: routesHandler,
  theme: lightThemeData(context),
  darkTheme: darkThemeData(context),
  debugShowCheckedModeBanner: false,
);

然后我为浅色主题和深色主题创建了两个ThemeData函数,并为每一个创建了一个colorScheme,这就是lightThemeColors(context)darkThemeColors(context)的样子

ColorScheme lightThemeColors(context) {
  return const ColorScheme(
    brightness: Brightness.light,
    primary: Color(0xFF202020),
    onPrimary: Color(0xFF505050),
    secondary: Color(0xFFBBBBBB),
    onSecondary: Color(0xFFEAEAEA),
    error: Color(0xFFF32424),
    onError: Color(0xFFF32424),
    background: Color(0xFFF1F2F3),
    onBackground: Color(0xFFFFFFFF),
    surface: Color(0xFF54B435),
    onSurface: Color(0xFF54B435),
  );
}

ColorScheme darkThemeColors(context) {
  return const ColorScheme(
    brightness: Brightness.dark,
    primary: Color(0xFFF1F2F3),
    onPrimary: Color(0xFFFFFFFF),
    secondary: Color(0xFFBBBBBB),
    onSecondary: Color(0xFFEAEAEA),
    error: Color(0xFFF32424),
    onError: Color(0xFFF32424),
    background: Color(0xFF202020),
    onBackground: Color(0xFF505050),
    surface: Color(0xFF54B435),
    onSurface: Color(0xFF54B435),
  );
}

这是两个ThemeData函数,分别用于明暗主题。

ThemeData lightThemeData(BuildContext context) {
  return ThemeData(
    scaffoldBackgroundColor: Theme.of(context).colorScheme.background,
    textTheme: textTheme(context),
    appBarTheme: appBarTheme(context),
    inputDecorationTheme: inputDecorationData(context),
    colorScheme: lightThemeColors(context),
  );
}

ThemeData darkThemeData(BuildContext context) {
  return ThemeData(
    scaffoldBackgroundColor: Theme.of(context).colorScheme.background,
    textTheme: textTheme(context),
    appBarTheme: appBarTheme(context),
    inputDecorationTheme: inputDecorationData(context),
    colorScheme: darkThemeColors(context),
  );
}

现在问题出在scaffoldBackgroundColorappBarThemeinputDecorationTheme上。
它只是忽略了scaffoldBackgroundColor,并使用默认的light blue
appBarTheme中,我尝试访问之前在colorScheme函数中定义的颜色,但不幸的是,什么也没发生,colorScheme被忽略了。

appBarTheme(context) {
  return AppBarTheme(
    backgroundColor: Theme.of(context).colorScheme.background,
    titleTextStyle: Theme.of(context).textTheme.headline5?.copyWith(color: Theme.of(context).colorScheme.primary),
  );
}

同样的情况也发生在inputDecorationTheme中,当我试图更改fillColorhintStyle的颜色时,它也会忽略它们。

InputDecorationTheme inputDecorationData(context) {
  return InputDecorationTheme(
    filled: true,
    fillColor: Theme.of(context).colorScheme.onBackground,
    hintStyle: Theme.of(context).textTheme.bodyText1?.copyWith(color: Theme.of(context).colorScheme.onSecondary),
  );
}
fdbelqdn

fdbelqdn1#

lightThemeData内部,你调用scaffoldBackgroundColor: Theme.of(context).colorScheme,它将返回默认的主题数据,因为Theme小部件在代码执行时不存在。在这种情况下,flutter返回默认的主题。
您应该尝试使用scaffoldBackgroundColor: lightThemeColors(context).backgroundColor

相关问题