Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen for changes to platformBrightness in Flutter?

Tags:

flutter

themes

I'm setting up a system where when the user changes the system theme to dark mode, it changes the theme and with Flutter, it works all well and good! However, when the user changes the system theme, the system navigation and status bar don't change their colors. I have code running on the home page inside the build method but that doesn't seem to do it. Here's the code inside the home page build method:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Brightness sysBrightness = MediaQuery.of(context).platformBrightness;
    if (sysBrightness == Brightness.dark)
      Themes.setDarkSystemColors();
    else
      Themes.setLightSystemColors();

    return Scaffold(
      appBar: CustomAppBar(title: "Home"),
      drawer: CustomDrawer(),
      body: SizedBox(),
    );
  }
}

Here's the code in the main app with theme: and darkTheme::

    return MaterialApp(
      initialRoute: '/',
      routes: routes,
      navigatorObservers: [_routeObserver],
      theme: Themes.lightTheme,
      darkTheme: Themes.darkTheme,
      debugShowCheckedModeBanner: false,
      title: 'School Life',
    );
like image 582
Benjamin Avatar asked Dec 13 '22 10:12

Benjamin


1 Answers

Override initState method and use onPlatformBrightnessChanged:

@override
void initState() {
  super.initState();
  final window = WidgetsBinding.instance.window;

  // This callback is called every time the brightness changes.
  window.onPlatformBrightnessChanged = () {
    final brightness = window.platformBrightness;
  };
}

To handle default behavior, add the following line in above callback. Thanks to @DJafari

WidgetsBinding.instance.handlePlatformBrightnessChanged();
like image 188
CopsOnRoad Avatar answered Jan 12 '23 01:01

CopsOnRoad