颤动:如何在运行时更改主题亮度?

问题描述 投票:4回答:2

我有一个MaterialAppThemeData,最初设置为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,
        );
      },
    );
  }
}
flutter material-design
2个回答
2
投票

问题是ThemeData在构造函数中使用其brightness值来合成许多其他颜色,但是当ThemeData发生变异时,这些颜色不会被重新计算。因此,解决方案是实例化一个全新的ThemeData而不是使用appTheme.copyWith(...)

改变这个:

appTheme.copyWith(
  brightness: _brightness,
),

对此:

ThemeData(
  brightness: _brightness,
),

0
投票

您可以查看以下图书馆:https://github.com/Norbert515/dynamic_theme

它允许您在运行时动态更改应用程序的整个主题数据或亮度。

© www.soinside.com 2019 - 2024. All rights reserved.