How to check if dark mode is enabled on iOS/Android using Flutter?
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(),
Solution 1:
There are two ways:
-
NO
context
required. Can be used ininitState
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;
Solution 2:
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.