Issue
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',
);
Solution
Override initState
method and use onPlatformBrightnessChanged
:
@override
void initState() {
super.initState();
var window = WidgetsBinding.instance!.window;
// This callback is called every time the brightness changes.
window.onPlatformBrightnessChanged = () {
var brightness = window.platformBrightness;
};
}
To handle default behavior, add the following line in above callback. Thanks to @DJafari
WidgetsBinding.instance?.handlePlatformBrightnessChanged();
Answered By - CopsOnRoad
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.