Home » Android » How to check if Android Q dark mode is enabled in Flutter?

How to check if Android Q dark mode is enabled in Flutter?

Posted by: admin May 14, 2020 Leave a comment

Questions:

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(),
How to&Answers:

You can check it using MediaQuery.

var brightness = MediaQuery.of(context).platformBrightness;
if (brightness == Brightness.dark)
  print("Dark mode");
else
  print("Normal mode");

Answer:

I found the way. Here it is.

  bool _darkModeEnabled = false;

  void _checkIfDarkModeEnabled() {
    final ThemeData theme = Theme.of(context);
    theme.brightness == appDarkTheme().brightness
        ? _darkModeEnabled = true
        : _darkModeEnabled = false;
  }

Answer:

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.