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,
);
},
);
}
}
Implementation. Brightness get brightness => colorScheme. brightness; Flutter.
Steps to change theme text color in Flutter You can change theme text color in Flutter, by defining the TextTheme (inside MaterialApp) and then adding headings type. For example, headline1 , headline2 , BodyText1 , and so on. After that, you can assign the TextStyle widget with the color of your choice.
The simplest way of changing the light to dark is by changing the theme of the MaterialApp widget to light to dark. For that, we need two themes like dark and light. ThemeData _darkTheme = ThemeData( accentColor: Colors. red, brightness: Brightness.
The issue is that ThemeData
uses its brightness
value in the constructor to synthesize a number of other colors, but those colors are not re-calculated when ThemeData
is mutated. Therefore, the solution is to instantiate an entirely new ThemeData
rather than use appTheme.copyWith(...)
.
Change this:
appTheme.copyWith(
brightness: _brightness,
),
To this:
ThemeData(
brightness: _brightness,
),
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