如何使用新的 ThemeData 重绘整个应用程序?
How to redraw whole app with new ThemeData?
我有 2 个 ThemeData
变量和一个 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
重新绘制应用程序?
您可能需要考虑将 MaterialApp
嵌套在 StatefulWidget
中
Flutter Gallery 示例应用在其 GalleryApp 小部件中执行此操作。
- 使用简单、轻便的 StatefulWidget class 例如GalleryApp
- 创建相应的GalleryAppState class.
- 这个class有
GalleryTheme _galleryTheme
实例变量
- 您需要 set/change 此值在 setState() method [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,
);
}
}
我有 2 个 ThemeData
变量和一个 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
重新绘制应用程序?
您可能需要考虑将 MaterialApp
嵌套在 StatefulWidget
Flutter Gallery 示例应用在其 GalleryApp 小部件中执行此操作。
- 使用简单、轻便的 StatefulWidget class 例如GalleryApp
- 创建相应的GalleryAppState class.
- 这个class有
GalleryTheme _galleryTheme
实例变量 - 您需要 set/change 此值在 setState() method [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,
);
}
}