Home > Software engineering >  Why dose MediaQuery.of(context).platformBrightness not working?
Why dose MediaQuery.of(context).platformBrightness not working?

Time:01-16

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?

CodePudding user response:

First make sure that you have added both ThemeModes in Material App itself:

Here's the example:

    return MaterialApp(
      title: "Dark",
      debugShowCheckedModeBanner: false,
      theme: ThemeData.copywith(brightness: Brightness.light),
      darkTheme: ThemeData.copywith(brightness: Brightness.dark),
      themeMode: ThemeMode.light,
    );

CodePudding user response:

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 is enabled or not. Just use:

 bool isDarkMode = Theme.of(context).brightness == Brightness.dark;
  print(isDarkMode);

and it prints the correct value of the bool. Let me know if you have a different information.

  • Related