I'm trying to create a dark theme based on an existing light theme using lightTheme.copyWith(brightness: Brightness.dark)
. However, the app seems to ignore the brightness of the dark theme.
My main.dart uses the following code:
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: Themes.lightTheme,
darkTheme: Themes.darkTheme,
themeMode: ThemeMode.dark,
...
);
}
where the Themes.lightTheme
and Themes.darkTheme
are defined as follows:
class Themes {
static ThemeData get lightTheme => ThemeData(
colorSchemeSeed: Colors.green,
);
static ThemeData get darkTheme => lightTheme.copyWith(
brightness: Brightness.dark,
);
}
The debugger shows that the dark theme contains brightness: Brightness.dark
.
However, all is working fine when I define the dark theme as follows without copyWith
:
class Themes {
static ThemeData get lightTheme => ThemeData(
colorSchemeSeed: Colors.green,
);
static ThemeData get darkTheme => ThemeData(
colorSchemeSeed: Colors.green,
brightness: Brightness.dark,
);
}
Could anyone point me out my blind spot of Dart/Flutter knowledge and explain what happens?
Environment:
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.29.3, on Microsoft Windows [Version 10.0.22631.5262], locale xx-XX)
[✓] Windows Version (11 Home 64-bit, 23H2, 2009)
[✓] Android toolchain - develop for Android devices (Android SDK version 35.0.1)
[✓] Chrome - develop for the web
[✓] Visual Studio - develop Windows apps (Visual Studio Community 2022 17.13.6)
[✓] Android Studio (version 2024.3)
[✓] VS Code (version 1.99.3)
[✓] Connected device (3 available)
[✓] Network resources
The issue here is that simply using lightTheme.copyWith(brightness: Brightness.dark)
does not fully convert the theme into a proper dark theme.
While brightness:Brightness.dark
does update the brightness field, it doesn't correctly update the other theme properties like background colors, text colors, and default styling that come with a true dark theme. These are generated internally by Flutter when you explicitly create a theme with brightness: Brightness.dark.
Solution:
Define your dark theme separately using ThemeData
with brightness: Brightness.dark
, like you did here:
static ThemeData get darkTheme => ThemeData(colorSchemeSeed: Colors.green, brightness: Brightness.dark,);
This ensures that all theme-related properties align correctly for a dark theme.