gpt4 book ai didi

Flutter:如何在运行时更改 MaterialApp 主题

转载 作者:IT老高 更新时间:2023-10-28 12:42:49 26 4
gpt4 key购买 nike

我有一个 MaterialApp设置 theme 的小部件适用于应用程序内的所有小部件。我想更改 MaterialApp小号 theme运行时来自没有直接引用其父级的子 Widget 的值 MaterialApp .

这似乎应该是可能的,因为 ThemeDataInheritedWidget 提供,但我不知道如何更改 theme批发的。有谁知道怎么做?

这里是 MaterialApp拥有应用程序的其余部分:

new MaterialApp(
title: 'App Name',
theme: initialTheme,
routes: <String, WidgetBuilder>{
'/' : ...,
},
),

最佳答案

根据 Dan Field 的建议,我得出了以下解决方案。如果有人有改进,请随时加入:

// 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;
}

}

关于Flutter:如何在运行时更改 MaterialApp 主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49164592/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com