如何使用新的ThemeData重绘整个应用程序?

时间:2018-03-17 16:11:56

标签: dart flutter

我有2 ThemeData个vars和SwitchListTile,代码如下:

new SwitchListTile(
                      value: applyDarkTheme,
                      title: const Text('Appy dark theme?'),
                      onChanged: (bool value) {
                        setState(() {
                          applyDarkTheme = value;
                        });
                      })

applyDarkTheme是我在第一次创建应用时检查的变量:

return new MaterialApp(
  title: 'Test Application',
  home: new MyHomePage(title: 'Test app'),
  theme: settings.applyDarkTheme ? AppThemes.dark : AppThemes.light,
  routes: _routes,
);

当我更改开关状态时,如何使用新的ThemeData重绘应用程序?

1 个答案:

答案 0 :(得分:1)

您可能需要考虑将MaterialApp嵌套在StatefulWidget

Flutter Gallery示例应用程序在GalleryApp小部件中执行此操作。

  • 使用简单明了的StatefulWidget类,例如GalleryApp
  • 创建相应的GalleryAppState类。
  • 此类具有GalleryTheme _galleryTheme实例变量
  • 您需要在setState()方法 [ref]
  • 中设置/更改此值
  • 然后,您可以pass this将它们添加到MaterialApp构造函数

以下是修改后的代码段

class GalleryApp extends StatefulWidget {
  @override
  GalleryAppState createState() => new GalleryAppState();
}

class GalleryAppState extends State<GalleryApp> {
  GalleryTheme _galleryTheme = kAllGalleryThemes[0];
  ...

  @override
  Widget build(BuildContext context) {
    Widget home = new GalleryHome(
      galleryTheme: _galleryTheme,
      onThemeChanged: (GalleryTheme value) {
        setState(() {
          _galleryTheme = value;
        });
      },
      ...
    );

    ...

    return new MaterialApp(
      ...
      home: home,
    );
  }
}
相关问题