How can I check if dark mode is enabled in Android Q with Flutter?
I know how to set the dark mode, but I didn't find a way to check the background theme.
Here is the code to set the dark theme.
darkTheme: ThemeData.dark(),
Dark mode can be detected by using the userInterfaceStyle property on the current trait collection. When it's set to dark you know that the current appearance is set to dark.
The simplest way of changing the light to dark is by changing the theme of the MaterialApp widget to light to dark. For that, we need two themes like dark and light. ThemeData _darkTheme = ThemeData( accentColor: Colors. red, brightness: Brightness.
There are two ways:
NO context
required. Can be used in initState
for example:
var brightness = SchedulerBinding.instance!.window.platformBrightness;
bool isDarkMode = brightness == Brightness.dark;
context
is required:
var brightness = MediaQuery.of(context).platformBrightness;
bool isDarkMode = brightness == Brightness.dark;
If you define a dark theme in your MaterialApp
, your app will automatically go dark when Android Q dark theme is enabled. You have to specify your dark theme like this:
MaterialApp(
theme: ThemeData(
brightness: Brightness.light,
primaryColor: Colors.red,
),
darkTheme: ThemeData(
brightness: Brightness.dark,
),
);
According to this medium article,
Now when you toggle Dark Theme in your system drawer, your Flutter app will automatically switch from your regular theme to your darkTheme!
However, if you want to manually check whether you're on dark mode, you can easily write a method using the Platform Channel API. More details here. As for the native code, check here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With