Flutter深色模式适配的实现

2022-07-24,,

一、简介

flutter的深色模式以及跟随系统设置比较简单,我感觉需要注意的是开发过程中尽量使用theme中的颜色与样式,开发过程中遇到的比较大的坑就是provider的一些问题,可能是因为我用的版本新一些,网上找了很多文章,总会遇到一些问题。本文的深色模式适配是通过修改thememode来实现的,供诸位有缘人参考。

二、环境介绍

1. flutter: 2.0.3
2. dart: 2.12.0
3. provider: 5.0.0
状态管理,用于运行时切换主题
4. shared_preferences: 2.0.5
数据持久化,用于保存当前选中的主题,以便下次启动时读取使用用户选择的主题

environment:
 sdk: ">=2.12.0 <3.0.0"

dependencies:
 flutter:
 sdk: flutter

 # 忽略了一些依赖...

 # shared_preferences https://pub.flutter-io.cn/packages/shared_preferences
 shared_preferences: ^2.0.5
 # 全局状态管理 https://github.com/rrousselgit/provider/blob/master/resources/translations/zh-cn/readme.md
 provider: ^5.0.0

三、主题

1. themedata

factory themedata({
 brightness brightness, // 应用主题亮度,可选(dark、light)
 visualdensity visualdensity, // 视觉密度
 materialcolor primaryswatch, // 主要样式,设置primarycolor后该背景色会被覆盖
 color primarycolor, // 主要部分背景颜色(导航和tabbar等)
 brightness primarycolorbrightness, // primarycolor的亮度
 color primarycolorlight, // primarycolor的浅色版
 color primarycolordark, // primarycolor的深色版
 color accentcolor, // 前景色(文本,按钮等)
 brightness accentcolorbrightness, // accentcolor的亮度
 color canvascolor, // materialtype.canvas 的默认颜色
 color shadowcolor, // 阴影颜色
 color scaffoldbackgroundcolor, // scaffold的背景颜色。典型material应用程序或应用程序内页面的背景颜色
 color bottomappbarcolor, // bottomappbar的默认颜色
 color cardcolor, // card的颜色
 color dividercolor, // divider和popupmenudivider的颜色,也用于listtile之间、datatable的行之间等。
 color focuscolor, // 突出颜色
 color hovercolor, // hovercolor
 color highlightcolor, // 高亮颜色,选中在泼墨动画期间使用的突出显示颜色,或用于指示菜单中的项。
 color splashcolor, // 墨水飞溅的颜色。inkwell
 interactiveinkfeaturefactory splashfactory, // 定义由inkwell和inkresponse反应产生的墨溅的外观。
 color selectedrowcolor, // 用于突出显示选定行的颜色。
 color unselectedwidgetcolor, // 用于处于非活动(但已启用)状态的小部件的颜色。例如,未选中的复选框。通常与accentcolor形成对比。也看到disabledcolor。
 color disabledcolor, // 禁用状态下部件的颜色,无论其当前状态如何。例如,一个禁用的复选框(可以选中或未选中)。
 color buttoncolor, // raisedbutton按钮中使用的material 的默认填充颜色。
 buttonthemedata buttontheme, // 定义按钮部件的默认配置,
 togglebuttonsthemedata togglebuttonstheme, // 切换按钮的主题
 color secondaryheadercolor, // 选定行时paginateddatatable标题的颜色。
 color textselectioncolor, // 文本框中文本选择的颜色,如textfield
 color cursorcolor, // 文本框中光标的颜色,如textfield
 color textselectionhandlecolor, // 调整当前选定的文本部分的句柄的颜色。
 color backgroundcolor, // 与主色形成对比的颜色,例如用作进度条的剩余部分。
 color dialogbackgroundcolor, // dialog元素的背景颜色
 color indicatorcolor, // 选项卡中选定的选项卡指示器的颜色。
 color hintcolor, // 用于提示文本或占位符文本的颜色,例如在textfield中。
 color errorcolor, // 用于输入验证错误的颜色,例如在textfield中
 color toggleableactivecolor, // 用于突出显示switch、radio和checkbox等可切换小部件的活动状态的颜色。
 string fontfamily, // 文本字体
 texttheme texttheme, // 文本的颜色与卡片和画布的颜色形成对比。
 texttheme primarytexttheme, // 与primarycolor形成对比的文本主题
 texttheme accenttexttheme, // 与accentcolor形成对比的文本主题。
 inputdecorationtheme inputdecorationtheme, // 基于这个主题的 inputdecorator、textfield和textformfield的默认inputdecoration值。
 tabbartheme tabbartheme, // 用于自定义选项卡栏指示器的大小、形状和颜色的主题。
 tooltipthemedata tooltiptheme, // tooltip主题
 cardtheme cardtheme, // card的颜色和样式
 appbartheme appbartheme, // appbar主题
 colorscheme colorscheme, // 拥有13种颜色,可用于配置大多数组件的颜色。
 navigationrailthemedata navigationrailtheme, // 导航边栏主题
 // ...
 })

2. main.dart or materialapp

theme为默认主题,darktheme为深色主题,thememode为当前使用哪个主题,可选值system、light、dark,只有在th``eme与darktheme都设置的时候才会生效,我们的theme与darktheme都直接使用themedata对象,给他指定了brightness,而不是使用这样感觉可以方便修改样式,当然也可以抽出来封装一下,我这没有去处理。

materialapp(
 theme: themedata(
 brightness: brightness.light,
 // scaffoldbackgroundcolor: color(0xfff5f5f9),
 ),
 darktheme: themedata(
 brightness: brightness.dark,
 // scaffoldbackgroundcolor: color(0xfff5f5f9),
 ),
 thememode: context.watch<thememodel>().theme
);

四、全局配置

全局配置是在materialapp加载之前进行一写初始化操作,参考了《flutter实战》电子书,flutter当中sharedpreferences是异步初始化,还有dio网络请求的缓存也需要提前初始化,我们这里sharedpreferences加载完之后在进行之后的操作,sputils中的sharedpreferences使用的global全局配置中的静态属性。

1. global

class global {
 static late sharedpreferences prefs;

 static thememode theme = thememode.light;

 // 是否为release版
 static bool get isrelease => bool.fromenvironment("dart.vm.product");

 //初始化全局信息,会在app启动时执行
 static future init() async {
 widgetsflutterbinding.ensureinitialized();
 prefs = await sharedpreferences.getinstance();

 // 当前本地存储的主题
 string themevalue = await sputils.instance.getstorage(spconstants.skin);
 theme = themestringtothememode(themevalue);

 //初始化网络请求相关配置
 httpmanager();
 }
}

2. main.dart

// global加载完成后掉用runapp
global.init().then((e) => runapp());

3. themestringtothememode()

字符串转thememode

thememode themestringtothememode(string themevalue){
 thememode theme = thememode.light;
 switch (themevalue) {
 case "light":
  theme = thememode.light;
  break;
 case "dark":
  theme = thememode.dark;
  break;
 case "system":
  theme = thememode.system;
  break;
 }
 return theme;
}

五、使用状态管理(provider)切换主题

> 此处大坑,处处劝退,感谢flutter provider劝退经历这篇文章

1. 构建主题model

class thememodel extends changenotifier {

 // 获取当前主题,如果为设置主题,则默认使用浅色模式
 thememode get theme => global.theme;

 // 主题改变后,通知其依赖项,新主题会立即生效
 set theme(thememode thememode) {
 if (thememode != theme) {
  global.theme = thememode;
  notifylisteners();
 }
 }
}

2. main.dart(监听值变化)

此处为main.dart文件的完整代码,下面有关provider的一些使用方式可能与网上很多文章不一样的,但是这都是官网文档的最新推荐使用方式。读取当前provider中存储的主题context.watch<thememodel>().theme

void main() {
 //顶部状态栏透明
 systemchrome.setsystemuioverlaystyle(
  systemuioverlaystyle(statusbarcolor: colors.transparent));
 global.init().then((e) => runapp(
  multiprovider(
   providers: [listenableprovider<thememodel>(create: (_) => thememodel())],
   builder: (context, child) {
    return wanandroid();
   }),
  ));
}

class wanandroid extends statelesswidget {
 // this widget is the root of your application.
 @override
 widget build(buildcontext context) {
 return materialapp(
  initialroute: '/',
  theme: themedata(
  brightness: brightness.light,
  // scaffoldbackgroundcolor: color(0xfff5f5f9),
  ),
  darktheme: themedata(
  brightness: brightness.dark,
  // scaffoldbackgroundcolor: color(0xfff5f5f9),
  ),
  thememode: context.watch<thememodel>().theme,
  routes: {
  '/': (context) => splashpage(),
  '/index': (context) => indexpage(),
  '/login': (context) => loginpage(),
  '/setting': (context) => settingpage(),
  },
  title: '玩android-flutter版',
 );
 }
}

3. 切换主题

修改provider中保存的值即可。

// themestringtothememode方法代码在上面有写
context.read<thememodel>().theme = themestringtothememode(value);

六、源码

- 源码:

到此这篇关于flutter深色模式适配的实现的文章就介绍到这了,更多相关flutter深色模式适配内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《Flutter深色模式适配的实现.doc》

下载本文的Word格式文档,以方便收藏与打印。