我有一个MaterialApp
与ThemeData
,最初设置为Brightness.light
。我想在运行时将亮度切换到Brightness.dark
,但是当我进行更改时,只有状态栏会发生变化 - 所有Flutter小部件都没有实际改变亮度。
如何实现这种行为?
要在运行时更改ThemeData
,我创建了以下StatefulWidget
,它包装了我的MaterialApp
并在主题更改时重建它:
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,
);
},
);
}
}
问题是ThemeData
在构造函数中使用其brightness
值来合成许多其他颜色,但是当ThemeData
发生变异时,这些颜色不会被重新计算。因此,解决方案是实例化一个全新的ThemeData
而不是使用appTheme.copyWith(...)
。
改变这个:
appTheme.copyWith(
brightness: _brightness,
),
对此:
ThemeData(
brightness: _brightness,
),
您可以查看以下图书馆:https://github.com/Norbert515/dynamic_theme
它允许您在运行时动态更改应用程序的整个主题数据或亮度。