news 2026/8/7 20:21:09

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/8/7 8:10:16

从蓝图到产线:高效产品信息传递的桥梁建设

在制造业中&#xff0c;研发设计的精妙构思与生产部门的高效执行之间&#xff0c;存在着一条至关重要的信息传递链。这条链路的畅通与否&#xff0c;直接决定了产品能否从图纸精准、准时地转化为合格的商品。本文将深入探讨这一过程的标准实践、常用工具、潜在挑战及其优化方案…

作者头像 李华
网站建设 2026/8/8 0:34:32

时间复杂度

这种题目是数据结构与算法考研&#xff08;如408&#xff09;或面试中的高频送分题&#xff0c;但也是高频陷阱题。 复习这类题目&#xff0c;不要靠“猜”或者“死记硬背”&#xff0c;而是要掌握一套**“数学建模”**的方法。一旦你建立了数学直觉&#xff0c;这类题看一眼就…

作者头像 李华
网站建设 2026/8/7 7:36:00

网站建设公司怎么选?2025年网站设计制作公司推荐指南

在数字化转型加速的2025年&#xff0c;企业网站已从基础展示工具升级为品牌价值载体与业务增长引擎。面对市场上众多的网站建设服务商&#xff0c;企业如何选择真正具备专业设计能力、技术实力与可靠服务的合作伙伴成为关键考量。本文通过对蒙特网站、IPG、电通等多家网站建设公…

作者头像 李华
网站建设 2026/8/7 22:11:51

今天咱们来聊一个挺有意思的优化算法改进——基于透镜成像反向策略的海洋捕食者算法。这个改进版本在原始MPA基础上搞了点新花样,咱们直接上干货看代码实现

基于透镜成像反向策略的多策略改进海洋捕食者优化算法 算法改进先看这个反向策略的实现。透镜成像反向学习可不是简单的镜像对称&#xff0c;它通过引入缩放因子让反向解更灵活。咱们来看这段关键代码&#xff1a; def lens_opposite(position, lb, ub, alpha0.8):focal_point …

作者头像 李华
网站建设 2026/8/7 20:18:53

Gitee:本土化DevOps平台如何重塑中国开发者生态

Gitee&#xff1a;本土化DevOps平台如何重塑中国开发者生态 在数字化转型浪潮席卷全球的当下&#xff0c;中国开发者正迎来前所未有的机遇与挑战。作为国内领先的一站式DevOps平台&#xff0c;Gitee凭借其独特的本土化优势&#xff0c;正在重新定义代码托管与协作开发的行业标准…

作者头像 李华
网站建设 2026/8/7 20:19:10

vCenter Server 8.0U3h 新增功能简介

VMware vCenter Server 8.0U3h 发布 - 集中管理 vSphere 环境 Server Management Software | vCenter 请访问原文链接&#xff1a;https://sysin.org/blog/vmware-vcenter-8-u3/ 查看最新版。原创作品&#xff0c;转载请保留出处。 作者主页&#xff1a;sysin.org vSphere 8…

作者头像 李华