因为练习开发模仿的是微信,微信又有暗黑和白色两种主题色。所以今天研究下主题色的适配。
在iOS 13 和 android 10 之后的系统上添加了新特性,暗黑模式(darkMode) 可以实现随着系统主题模式的切换而进行app跟随的功能,下面就将在flutter项目中进行暗黑模式的适配工作。
首先在main文件下:
添加三个属性
ThemeMode有三种模式,
enum ThemeMode {
/// Use either the light or dark theme based on what the user has selected in
/// the system settings.
system,
/// Always use the light mode regardless of system preference.
light,
/// Always use the dark mode (if available) regardless of system preference.
dark,
}
配置好以上代码编译后:
导航栏和图标选中的颜色都是蓝色。 接下来修改这个颜色。
首先需要自定义这个属性:
final ThemeData? theme;
但是他接收的是
ThemeData({
Brightness brightness, //深色还是浅色
MaterialColor primarySwatch, //主题颜色样本
Color primaryColor, //主色,决定导航栏颜色
Color accentColor, //次级色,决定大多数Widget的颜色,如进度条、开关等。
Color cardColor, //卡片颜色
Color dividerColor, //分割线颜色
ButtonThemeData buttonTheme, //按钮主题
Color cursorColor, //输入框光标颜色
Color dialogBackgroundColor,//对话框背景颜色
String fontFamily, //文字字体
TextTheme textTheme,// 字体主题,包括标题、body等文字样式
IconThemeData iconTheme, // Icon的默认样式
TargetPlatform platform, //指定平台,应用特定平台控件风格
...
})
这里primarySwatch接受的是MaterialColor类型,直接给Color会报错。
可以写一个函数吧Color转换为MaterialColor,函数如下。
MaterialColor createMaterialColor(Color color) {
List strengths = <double>[.05];
Map<int, Color> swatch = <int, Color>{};
final int r = color.red, g = color.green, b = color.blue;
for (int i = 1; i < 10; i++) {
strengths.add(0.1 * i);
}
strengths.forEach((strength) {
final double ds = 0.5 - strength;
swatch[(strength * 1000).round()] = Color.fromRGBO(
r + ((ds < 0 ? r : (255 - r)) * ds).round(),
g + ((ds < 0 ? g : (255 - g)) * ds).round(),
b + ((ds < 0 ? b : (255 - b)) * ds).round(),
1,
);
});
return MaterialColor(color.value, swatch);
}
这样就可以自定义颜色:
theme: ThemeData(
primarySwatch: createMaterialColor(Color.fromRGBO(233, 233, 233, 1)),
),
运行程序后发现Icon选中颜色为primarySwatch设置的灰色。
然后可以在bottomNavigationBar中设置Icon选中的颜色。
再次编译程序,达到理想的效果,下面为dark和light的效果图:
.
在设置themeMode为system后,在苹果手机上编译可以正常识别系统主题。完美👌🏻
themeMode: ThemeMode.system,
当然这只是简单的主题切换 后续还有增加用户手动切换主题的功能,后续再在这里增加内容。