flutter 如何更改按钮时的抖动主题颜色

i5desfxk  于 2022-11-25  发布在  Flutter
关注(0)|答案(1)|浏览(185)

我正在尝试做一个应用程序与动态主题颜色我的想法是当用户点击一个按钮的应用程序的一些部分(按钮,应用程序栏,主题数据...)将改变。但我不知道如何做到这一点,我尝试了一些如果条件,和静态变量...但没有工作,任何想法如何做到这一点?
我想把3个不同的主题的应用程序,这里是主文件,我把应用程序的主题:

void main() {
  runApp(CharlotApp());
}

class CharlotApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Fluttter colors',
        theme: ThemeData(
          primaryColor: MyTheme.kPrimaryColor,
          accentColor: MyTheme.kAccentColor,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: SplashScreen());
  }
}
1l5u6lss

1l5u6lss1#

您可以使用在此link上共享的相同方法:

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

}

在要更改主题其他类中

setState(() {
    ThemeChanger.of(context).appTheme = appThemeLight;
  });

相关问题