I want to check if my Darkmode is enable or not so I did this:
@override
Widget build(BuildContext context) {
var brightness = MediaQuery.of(context).platformBrightness;
bool isDarkMode = brightness == Brightness.dark;
print(isDarkMode);
in the first widget which builds after the MaterialApp, but I always get false as print result, independently of the active Theme Mode. I also tried
var brightness = SchedulerBinding.instance.platformDispatcher.platformBrightness;
bool isDarkMode = brightness == Brightness.dark;
In the init state, but same problem
I checked if it’s the fault of my project, so I created a brand-new Project and used the adaptive_theme package – still same problem
Code of the Material:
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return AdaptiveTheme(
light: ThemeData(
brightness: Brightness.light,
primarySwatch: Colors.yellow,
backgroundColor: Colors.grey
),
dark: ThemeData(
brightness: Brightness.dark,
primarySwatch: Colors.red,
backgroundColor: Colors.blue,
),
builder: (theme, darkTheme)=>MaterialApp(
title: 'Flutter Demo',
theme: theme,
darkTheme: darkTheme,
home: const MyHomePage(title: 'Flutter Demo Home Page'),
), initial: AdaptiveThemeMode.light,
);
}
}
I call MediaQuery.of(context).platformBrightness inside the MyHomePageState.
Any advices what I do wrong?
2
Answers
Simpel answere to my question after a lot of research: In the current version ( 16.01.2022)
MediaQuery.of(context).platformBrightness;
is not the correct way to check if darkmode inside your app is enabled or not. This only works for checking which Theme the user uses on his system. For checking on app level just use:and it prints the correct value of the bool. Let me know if you have a different information.
First make sure that you have added both ThemeModes in Material App itself:
Here’s the example: