news 2026/6/10 13:50:38

Flutter OpenHarmony 运动App水分摄入追踪组件开发

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Flutter OpenHarmony 运动App水分摄入追踪组件开发

前言

水分摄入追踪是运动健康应用中帮助用户保持良好水合状态的重要功能。运动过程中和日常生活中保持充足的水分摄入对健康至关重要。本文将详细介绍如何在Flutter与OpenHarmony平台上实现水分摄入追踪组件,包括饮水记录、目标设定、提醒功能等模块的完整实现方案。

Flutter水分数据模型

classWaterIntake{finalStringid;finalint amount;finalDateTimetimestamp;finalStringtype;WaterIntake({requiredthis.id,requiredthis.amount,requiredthis.timestamp,this.type='water'});}classDailyWaterData{finalDateTimedate;finalint totalIntake;finalint targetIntake;finalList<WaterIntake>records;DailyWaterData({requiredthis.date,requiredthis.totalIntake,requiredthis.targetIntake,requiredthis.records,});doublegetprogress=>(totalIntake/targetIntake*100).clamp(0,100);boolgetisGoalReached=>totalIntake>=targetIntake;intgetremaining=>(targetIntake-totalIntake).clamp(0,targetIntake);StringgetstatusText{if(progress>=100)return'已达标 💧';if(progress>=75)return'即将达标';if(progress>=50)return'继续加油';return'需要多喝水';}}

水分数据模型定义了饮水记录和每日汇总数据。WaterIntake记录单次饮水的量、时间和类型(水、茶、咖啡等)。DailyWaterData汇总每日数据,包含总摄入量、目标量和记录列表。progress计算完成百分比,remaining计算还需摄入的量。statusText根据进度返回鼓励性文字。

OpenHarmony水分存储服务

importdataPreferencesfrom'@ohos.data.preferences';classWaterStorageService{privatepreferences:dataPreferences.Preferences|null=null;asyncinitialize(context:Context):Promise<void>{this.preferences=awaitdataPreferences.getPreferences(context,'water_intake');}asyncaddIntake(amount:number):Promise<void>{if(!this.preferences)return;lettoday=newDate().toISOString().split('T')[0];letrecordsJson=awaitthis.preferences.get(today,'[]')asstring;letrecords:Array<object>=JSON.parse(recordsJson);records.push({id:Date.now().toString(),amount:amount,timestamp:Date.now(),});awaitthis.preferences.put(today,JSON.stringify(records));awaitthis.preferences.flush();}asyncgetTodayIntake():Promise<number>{if(!this.preferences)return0;lettoday=newDate().toISOString().split('T')[0];letrecordsJson=awaitthis.preferences.get(today,'[]')asstring;letrecords:Array<object>=JSON.parse(recordsJson);returnrecords.reduce((sum:number,r:object)=>sum+(r['amount']asnumber),0);}asyncgetTargetIntake():Promise<number>{if(!this.preferences)return2000;returnawaitthis.preferences.get('target',2000)asnumber;}asyncsetTargetIntake(target:number):Promise<void>{if(this.preferences){awaitthis.preferences.put('target',target);awaitthis.preferences.flush();}}}

水分存储服务按日期存储饮水记录。addIntake方法添加新的饮水记录,getTodayIntake方法计算今日总摄入量。使用日期字符串作为键,每天的记录存储为JSON数组。目标摄入量单独存储,默认2000毫升。这种设计支持按天查询和统计。

Flutter水分显示组件

classWaterIntakeDisplayextendsStatelessWidget{finalDailyWaterDatadata;finalVoidCallbackonAddWater;constWaterIntakeDisplay({Key?key,requiredthis.data,requiredthis.onAddWater}):super(key:key);@overrideWidgetbuild(BuildContextcontext){returnCard(margin:EdgeInsets.all(16),child:Padding(padding:EdgeInsets.all(20),child:Column(children:[Stack(alignment:Alignment.center,children:[SizedBox(width:150,height:150,child:CircularProgressIndicator(value:data.progress/100,strokeWidth:12,backgroundColor:Colors.blue.withOpacity(0.2),valueColor:AlwaysStoppedAnimation(Colors.blue),),),Column(children:[Text('💧',style:TextStyle(fontSize:32)),Text('${data.totalIntake}',style:TextStyle(fontSize:32,fontWeight:FontWeight.bold)),Text('/${data.targetIntake}ml',style:TextStyle(color:Colors.grey)),],),],),SizedBox(height:16),Text(data.statusText,style:TextStyle(fontSize:16,color:data.isGoalReached?Colors.green:Colors.blue)),SizedBox(height:16),Row(mainAxisAlignment:MainAxisAlignment.spaceEvenly,children:[_buildQuickAddButton(100,onAddWater),_buildQuickAddButton(200,onAddWater),_buildQuickAddButton(300,onAddWater),_buildQuickAddButton(500,onAddWater),],),],),),);}Widget_buildQuickAddButton(int amount,VoidCallbackonTap){returnOutlinedButton(onPressed:onTap,child:Text('+${amount}ml'),);}}

水分显示组件以圆形进度环展示今日饮水进度。中央显示水滴emoji、当前摄入量和目标量。底部提供快速添加按钮,常用量100ml、200ml、300ml、500ml一键添加。状态文字根据进度变化,达标后显示绿色。这种设计让用户快速了解饮水情况并便捷记录。

OpenHarmony饮水提醒服务

importreminderAgentManagerfrom'@ohos.reminderAgentManager';classWaterReminderService{asyncsetHourlyReminder(startHour:number,endHour:number):Promise<Array<number>>{letreminderIds:Array<number>=[];for(lethour=startHour;hour<=endHour;hour+=2){letreminderRequest:reminderAgentManager.ReminderRequestAlarm={reminderType:reminderAgentManager.ReminderType.REMINDER_TYPE_ALARM,hour:hour,minute:0,daysOfWeek:[1,2,3,4,5,6,7],title:'💧 喝水提醒',content:'该喝水了,保持水分充足!',ringDuration:5,snoozeTimes:0,};letid=awaitreminderAgentManager.publishReminder(reminderRequest);reminderIds.push(id);}returnreminderIds;}asynccancelAllReminders(reminderIds:Array<number>):Promise<void>{for(letidofreminderIds){awaitreminderAgentManager.cancelReminder(id);}}}

饮水提醒服务设置定时提醒用户喝水。setHourlyReminder方法在指定时间范围内每2小时设置一个提醒,帮助用户养成规律饮水习惯。提醒内容简洁友好,使用水滴emoji增加亲和力。用户可以自定义提醒的开始和结束时间,避免夜间打扰。

Flutter饮水历史图表

classWaterHistoryChartextendsStatelessWidget{finalList<int>weeklyData;finalint target;constWaterHistoryChart({Key?key,requiredthis.weeklyData,requiredthis.target}):super(key:key);@overrideWidgetbuild(BuildContextcontext){List<String>days=['一','二','三','四','五','六','日'];returnContainer(height:200,padding:EdgeInsets.all(16),child:Row(crossAxisAlignment:CrossAxisAlignment.end,children:List.generate(7,(index){double percentage=weeklyData[index]/target;double height=(percentage.clamp(0,1.2))*120;bool reachedGoal=weeklyData[index]>=target;returnExpanded(child:Padding(padding:EdgeInsets.symmetric(horizontal:4),child:Column(mainAxisAlignment:MainAxisAlignment.end,children:[Text('${(weeklyData[index]/1000).toStringAsFixed(1)}L',style:TextStyle(fontSize:10)),SizedBox(height:4),Container(height:height,decoration:BoxDecoration(color:reachedGoal?Colors.blue:Colors.blue.withOpacity(0.5),borderRadius:BorderRadius.circular(4),),),SizedBox(height:4),Text(days[index],style:TextStyle(fontSize:12)),],),),);}),),);}}

饮水历史图表以柱状图展示一周的饮水情况。每根柱子高度按摄入量与目标的比例计算,达标的日期使用深蓝色,未达标使用浅蓝色。顶部显示具体升数,底部显示星期几。这种图表帮助用户回顾饮水习惯,发现需要改进的日期。

Flutter饮水设置组件

classWaterSettingsWidgetextendsStatefulWidget{finalint currentTarget;finalFunction(int)onTargetChanged;constWaterSettingsWidget({Key?key,requiredthis.currentTarget,requiredthis.onTargetChanged}):super(key:key);@overrideState<WaterSettingsWidget>createState()=>_WaterSettingsWidgetState();}class_WaterSettingsWidgetStateextendsState<WaterSettingsWidget>{late int _target;@overridevoidinitState(){super.initState();_target=widget.currentTarget;}@overrideWidgetbuild(BuildContextcontext){returnColumn(crossAxisAlignment:CrossAxisAlignment.start,children:[Text('每日目标',style:TextStyle(fontWeight:FontWeight.bold)),SizedBox(height:8),Text('$_targetml',style:TextStyle(fontSize:24,fontWeight:FontWeight.bold,color:Colors.blue)),Slider(value:_target.toDouble(),min:1000,max:4000,divisions:30,onChanged:(value){setState(()=>_target=value.toInt());widget.onTargetChanged(_target);},),SizedBox(height:8),Text('建议: 成人每日饮水量约2000-2500ml',style:TextStyle(color:Colors.grey,fontSize:12)),],);}}

饮水设置组件让用户自定义每日饮水目标。Slider范围1000-4000ml,覆盖不同人群的需求。底部提供健康建议作为参考。目标变化通过回调通知父组件保存。这种设置让用户可以根据自己的身体状况和运动量调整目标。

总结

本文全面介绍了Flutter与OpenHarmony平台上水分摄入追踪组件的实现方案。从数据模型到存储服务,从进度展示到定时提醒,涵盖了饮水追踪功能的各个方面。通过便捷的记录方式和及时的提醒,我们可以帮助用户养成良好的饮水习惯,保持身体水合状态。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/10 11:39:40

从竞合到自主:国产CAD软件的渐进替代战略

在全球制造业数字化转型与供应链安全日益重要的双重背景下&#xff0c;计算机辅助设计&#xff08;CAD&#xff09;软件领域的竞争正超越单纯的产品对比&#xff0c;进入一个以战略耐心和路径规划为特征的新阶段。核心共识在于&#xff1a;短期来看&#xff0c;国产与国际主流C…

作者头像 李华
网站建设 2026/6/10 11:40:33

个人微信二次开发:如何高效对接API接口?

在私域流量被视为企业“救命稻草”的今天&#xff0c;微信早已不仅是一个聊天工具&#xff0c;它更是一台价值万金的商业印钞机。但现实却让无数老板和运营主管头疼不已&#xff1a;人工成本像流水&#xff1a; 雇了一堆员工&#xff0c;每天却在机械地加好友、拉群、改公告&am…

作者头像 李华
网站建设 2026/6/10 11:42:49

API赋能:消金电销无缝联的革新实践

在消费金融行业&#xff08;消金&#xff09;的激烈竞争中&#xff0c;电销效率直接关乎业务成败。传统电销模式常因系统割裂、数据孤岛等问题导致接通率低、转化乏力。而API&#xff08;应用程序编程接口&#xff09;技术的深度应用&#xff0c;正推动消金电销向“无缝连接”时…

作者头像 李华
网站建设 2026/6/10 10:47:06

FPGA GPIO模块设计与APB接口实现解析

企业大厂应用级FPGA GPIO verilog完整模块ip源代码&#xff0c;apb接口&#xff0c;企业级应用源码&#xff0c;适合需要学习ic设计验证及soc开发的工程师。 提供databook资料和verilog完整ip源代码 代码架构清晰、规范&#xff0c;便于阅读理解&#xff0c;可直接应用&#xf…

作者头像 李华
网站建设 2026/6/10 11:11:38

本土项目管理工具Gitee如何重塑中国企业级DevOps生态

本土项目管理工具Gitee如何重塑中国企业级DevOps生态 在数字化转型浪潮席卷各行各业的当下&#xff0c;中国本土项目管理平台Gitee正以独特的本土化优势和安全合规能力&#xff0c;成为技术团队DevOps转型的首选方案。作为国内领先的一站式研发协作平台&#xff0c;Gitee不仅解…

作者头像 李华
网站建设 2026/6/10 11:38:40

小米发布大模型MiMo-V2-Flash,AiPy已率先上架

今天&#xff0c;Xiaomi MiMo大模型负责人罗福莉在2025小米人车家全生态合作伙伴大会上正式公布了MiMo-V2-Flash。据了解&#xff0c;该模型总参数量达3090亿&#xff0c;活跃参数为150亿&#xff0c;采用对开发者友好的MIT开源协议&#xff0c;基础版权重也已经在Hugging Face…

作者头像 李华