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',
);
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With