我是Flutter的初学者。 如何将整个应用程序主题从浅色主题更改为黑暗主题?
我们说我的灯光主题代码如下:
final ThemeData dTheme = new ThemeData(
primarySwatch: Colors.orange,
primaryColor: Colors.orangeAccent[100],
primaryColorBrightness: Brightness.light,
);
和黑暗主题:
final ThemeData lTheme = new ThemeData(
primarySwatch: Colors.indigo,
primaryColor: Colors.indigoAccent[100],
primaryColorBrightness: Brightness.dark,
);
我想在运行时单击按钮更改主题。
答案 0 :(得分:1)
这是这里回答的问题的具体情况:Force Flutter to redraw all widgets
查看该问题中提到的Stocks样本,特别注意: https://github.com/flutter/flutter/blob/master/examples/stocks/lib/main.dart https://github.com/flutter/flutter/blob/master/examples/stocks/lib/stock_settings.dart
请注意以下事项:
_configuration
指定的,由configurationUpdater
configurationUpdater
会传递给需要它的应用的子女下面的代码可能会对您有所帮助:
// How to use: Any Widget in the app can access the ThemeChanger
// because it is an InheritedWidget. Then the Widget can call
// themeChanger.theme = [blah] to change the theme. The ThemeChanger
// then accesses AppThemeState by using the _themeGlobalKey, and
// the ThemeChanger switches out the old ThemeData for the new
// ThemeData in the AppThemeState (which causes a re-render).
final _themeGlobalKey = new GlobalKey(debugLabel: 'app_theme');
class AppTheme extends StatefulWidget {
final child;
AppTheme({
this.child,
}) : super(key: _themeGlobalKey);
@override
AppThemeState createState() => new AppThemeState();
}
class AppThemeState extends State<AppTheme> {
ThemeData _theme = DEV_THEME;
set theme(newTheme) {
if (newTheme != _theme) {
setState(() => _theme = newTheme);
}
}
@override
Widget build(BuildContext context) {
return new ThemeChanger(
appThemeKey: _themeGlobalKey,
child: new Theme(
data: _theme,
child: widget.child,
),
);
}
}
class ThemeChanger extends InheritedWidget {
static ThemeChanger of(BuildContext context) {
return context.inheritFromWidgetOfExactType(ThemeChanger);
}
final ThemeData theme;
final GlobalKey _appThemeKey;
ThemeChanger({
appThemeKey,
this.theme,
child
}) : _appThemeKey = appThemeKey, super(child: child);
set appTheme(AppThemeOption theme) {
switch (theme) {
case AppThemeOption.experimental:
(_appThemeKey.currentState as AppThemeState)?.theme = EXPERIMENT_THEME;
break;
case AppThemeOption.dev:
(_appThemeKey.currentState as AppThemeState)?.theme = DEV_THEME;
break;
}
}
@override
bool updateShouldNotify(ThemeChanger oldWidget) {
return oldWidget.theme == theme;
}
}