news 2026/7/7 20:55:51

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/7/7 11:05:51

隐藏Gemini脚本

油猴脚本&#xff1a;// UserScript // name 强力隐藏 Gemini Logo // namespace http://tampermonkey.net/ // version 2.0 // description 通过多种特征&#xff08;链接、标签、位置&#xff09;强力隐藏左上角的 Gemini Logo&#xff0c;包含自动检测机制…

作者头像 李华
网站建设 2026/7/7 12:12:48

【计算机毕设】基于深度学习的人体摔倒识别方法与实现

&#x1f49f;博主&#xff1a;程序员&#xff1a;小俊SDN作者、博客专家、全栈领域优质创作者 &#x1f49f;专注于计算机毕业设计&#xff0c;大数据、深度学习、Java、小程序、python、安卓等技术领域 &#x1f4f2;文章末尾获取源码数据库 &#x1f308;还有大家在毕设选题…

作者头像 李华
网站建设 2026/7/7 3:09:10

一种“看起来很稳”,却暗藏坑点的恒流 PWM 驱动电路

最近看到有“电工猴”分享了一个恒流 PWM 驱动电路&#xff0c;第一眼看上去相当规整&#xff0c;功能也很诱人&#xff1a; 恒流 PWM&#xff0c;一步到位。 考虑到这种方案在实际项目中很可能会被用到&#xff0c;这里干脆系统拆一遍&#xff0c;顺便把其中的坑也挖出来给大…

作者头像 李华
网站建设 2026/7/7 12:51:25

国产DevOps平台Gitee如何重塑中国技术团队的协作范式?

国产DevOps平台Gitee如何重塑中国技术团队的协作范式&#xff1f; 在数字化转型浪潮下&#xff0c;中国技术团队正面临前所未有的协作效率挑战。作为本土领先的DevOps平台&#xff0c;Gitee通过深度适配国内开发环境的安全合规体系与全流程工具链&#xff0c;正在重新定义技术团…

作者头像 李华
网站建设 2026/7/7 11:25:48

低幻觉AI:重塑科研与教育领域的可信智能新范式

当AI的推理能力经得起数学猜想的严格检验&#xff0c;人机协作便从“工具使用”升华为“智能伙伴”关系 在AI技术迅猛发展的今天&#xff0c;一个核心痛点日益凸显&#xff1a;大模型幻觉问题。在科研领域&#xff0c;一个虚构的公式可能导致数月研究功亏一篑&#xff1b;在教…

作者头像 李华
网站建设 2026/7/6 9:26:04

一篇文章让你读懂_Cache / DMA / 一致性

Cache / DMA / 内存&#xff0c;在芯片里各自“眼里看到的世界”到底是什么样的&#xff1f;为什么它们天生就不一致&#xff1f;为什么“什么都不做”在工程上几乎一定是错的&#xff1f; 一、先统一一个世界观&#xff1a;芯片里根本不存在“同一份数据” 这是理解所有一致性…

作者头像 李华