Skip to content
DeveloperMemos

Detecting Dark Mode in Flutter

Flutter, Dark Mode, Mobile Development1 min read

In Flutter, adapting your app's UI to the user's system-wide dark mode preference enhances user experience. This article explores two methods to check for dark mode in your Flutter applications.

Using MediaQuery

The MediaQuery class provides access to various information about the current device and environment. You can leverage it to retrieve the user's preferred brightness setting and determine if dark mode is enabled.

Here's how to use MediaQuery to check for dark mode:

1bool isDarkMode = MediaQuery.of(context).platformBrightness == Brightness.dark;

Explanation:

  • MediaQuery.of(context): This retrieves the MediaQuery object associated with the current widget, providing access to device-specific information.
  • .platformBrightness: This property extracts the current platform's brightness setting (either Brightness.light or Brightness.dark).
  • Brightness.dark: This constant represents the dark brightness mode.

Using this method:

  1. Access the MediaQuery object using MediaQuery.of(context).
  2. Check if the .platformBrightness property equals Brightness.dark.

If the condition evaluates to true, dark mode is enabled on the user's device.

Using SchedulerBinding

The SchedulerBinding class offers another way to check for dark mode, particularly useful in scenarios where you don't have access to the build context (e.g., within the initState method of a StatefulWidget).

Here's how to use SchedulerBinding to check for dark mode:

1bool isDarkMode = SchedulerBinding.instance.platformDispatcher.platformBrightness == Brightness.dark;

Explanation:

  • SchedulerBinding.instance: This retrieves the scheduler binding for the current thread.
  • .platformDispatcher.platformBrightness: Similar to MediaQuery, this retrieves the platform's brightness setting.

Using this method:

  1. Access the SchedulerBinding using SchedulerBinding.instance.
  2. Check if the .platformDispatcher.platformBrightness property equals Brightness.dark.

Similar to MediaQuery, a true evaluation indicates dark mode is active.

Choosing the Right Method

The choice between these methods depends on the context in which you need to check for dark mode:

  • Use MediaQuery.of(context).platformBrightness when checking within the build method of a widget or anywhere with access to context.
  • Use SchedulerBinding.instance.platformDispatcher.platformBrightness when checking outside the build method (e.g., in initState).

Both methods effectively determine the user's dark mode preference. Select the one that best aligns with your development approach!