I have a MaterialApp
with a ThemeData
that is initially set to Brightness.light
. I'd like to switch the brightness to Brightness.dark
at runtime, but when I make that change, only the status bar changes - none of the Flutter widgets actually change their brightness.
How can this behavior be achieved?
To change the ThemeData
at runtime, I've created the following StatefulWidget
that wraps my MaterialApp
and rebuilds it whenever the theme changes:
final ThemeData appTheme = ThemeData(
brightness: Brightness.light,
);
class ThemeChanger extends StatefulWidget {
static ThemeChangerState of (BuildContext context) {
return context.ancestorStateOfType(TypeMatcher<ThemeChangerState>());
}
ThemeChanger({
this.childBuilder,
});
final Widget Function(BuildContext, ThemeData) childBuilder;
@override
ThemeChangerState createState() => ThemeChangerState();
}
class ThemeChangerState extends State<ThemeChanger> {
Brightness _brightness = Brightness.light;
set brightness(Brightness brightness) {
setState(() {
_brightness = brightness;
});
}
@override
Widget build(BuildContext context) {
return widget.childBuilder(
context,
appTheme.copyWith(
brightness: _brightness
),
);
}
}
// Then in main.dart
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return DemoTheme(
childBuilder: (BuildContext context, ThemeData theme) {
return MaterialApp(
title: 'Materially Better',
theme: theme,
routes: {
'/': (BuildContext context) {
return LoginScreen();
},
'home': (BuildContext context) {
return MainScreen();
}
},
debugShowCheckedModeBanner: false,
);
},
);
}
}
copyWith
instantiatesnew
instance of class. Just see the code of method. – Adjure