白天&黑天模式的颜色和图片不同,重点在于管理好颜色与图片
定义MyTheme初始化主题,并设置到MaterialApp
class ThemeHolder {
static bool isDarkMode = false;
static ThemeData theme;
static void init(bool isDark) {
isDarkMode = isDark;
final brightness = isDarkMode ? Brightness.dark : Brightness.light;
theme = ThemeData(brightness: brightness);
}
}
MaterialApp(
title: "Demo",
home: _DemoWidget(),
theme: ThemeHolder.theme,
localizationsDelegates: ThemeHolder.localizationsDelegates,
supportedLocales: ThemeHolder.supportedLocales,
)
颜色
class ColorHolder {
static const _colors = {
"title": [Color(0x********), Color(0x********)],
"subtitile": [Color(0x********), Color(0x********)],
};
static get title {
return color("title");
}
static Color color(String key) {
final colors = _colors[key];
if (colors == null) {
return Colors.black;
}
if (ThemeHolder.isDarkMode) {
if (colors.length == 2) {
return colors[1];
} else {
return colors[0];
}
} else {
return colors[0];
}
}
}
TextStyle(fontSize: 20, color: ColorHolder.title)
图片
- 资源存放
创建images和images_dark文件夹 - 资源声明
flutter:
assets:
- images/
- images_dark/
- 扩展String添加imageName(): String
extension ImageNames on String {
String imageName() {
return ThemeHolder.isDarkMode ? 'images_dark/$this' : 'images/$this';
}
}
- 使用
Image.asset('***.png'.imageName())