— Flutter, Dark Mode, Mobile Development — 1 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.
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:
MediaQuery object using MediaQuery.of(context)..platformBrightness property equals Brightness.dark.If the condition evaluates to true, dark mode is enabled on the user's device.
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:
SchedulerBinding using SchedulerBinding.instance..platformDispatcher.platformBrightness property equals Brightness.dark.Similar to MediaQuery, a true evaluation indicates dark mode is active.
The choice between these methods depends on the context in which you need to check for dark mode:
MediaQuery.of(context).platformBrightness when checking within the build method of a widget or anywhere with access to context.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!