Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if dark mode is enabled on iOS/Android using Flutter?

Tags:

flutter

dart

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(),
like image 545
R2T8 Avatar asked May 25 '19 11:05

R2T8


People also ask

How do I know if dark mode is enabled in Swift?

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.

How do you switch between dark and light mode in flutter?

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.


2 Answers

There are two ways:

  1. NO context required. Can be used in initState for example:

     var brightness = SchedulerBinding.instance!.window.platformBrightness;
     bool isDarkMode = brightness == Brightness.dark;
    
  2. context is required:

     var brightness = MediaQuery.of(context).platformBrightness;
     bool isDarkMode = brightness == Brightness.dark;
    
like image 170
CopsOnRoad Avatar answered Oct 26 '22 06:10

CopsOnRoad


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.

like image 29
Naeem Hasan Avatar answered Oct 26 '22 07:10

Naeem Hasan