Flutter 跨平台实战:OpenHarmony 健康管理应用 Day12|新增健康数据录入时间记录与展示功能
·
🎯Flutter 跨平台实战:OpenHarmony 健康管理应用 Day12|新增健康数据录入时间记录与展示功能
欢迎加入开源鸿蒙跨平台社区:https://openharmonycrossplatform.csdn.net
🚀 前言
大家好,本篇是 Flutter+OpenHarmony 健康管理应用开发系列第十二篇笔记。在 Day11 完成全局 UI 美化、主题配色与卡片样式统一的基础上,今日新增健康数据录入时间记录功能,保存数据时自动获取当前系统时间并持久化存储,在首页与个人中心展示最新录入时间,适配鸿蒙模拟器正常运行,代码可直接复制使用,适合课程实训作业提交与高分自查。
💥 本文你能学到
- Flutter 获取系统当前标准日期时间
- 利用 SharedPreferences 持久化存储录入时间
- 时间格式规范化拼接,统一展示样式
- 数据保存时自动同步更新时间记录
- 首页、个人中心卡片新增录入时间展示项
- 保留前期全部业务与 UI 美化样式,无功能冲突
🥝 开发环境
1. 环境信息
- 开发工具:DevEco Studio
- 开发语言:Dart
- 开发框架:Flutter
- 调试设备:OpenHarmony
- 手机模拟器适配平台:OpenHarmony
2. 依赖配置
无需新增依赖,沿用原有配置:
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.2.2
📝 今日核心开发功能
- 调用 DateTime 获取系统当前年月日时分
- 规范时间格式,拼接为标准可读时间字符串
- 保存健康信息同时同步存储录入时间
- 首页与个人中心信息卡片新增「录入时间」展示
- 清空数据时同步清空时间记录,恢复默认提示
- 保留表单校验、BMI 计算、全局 UI 美化、本地存储、一键清空所有原有功能
✅ 完整可运行代码
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "健康管理",
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.teal,
cardTheme: CardTheme(
elevation: 6,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
margin: EdgeInsets.symmetric(horizontal: 4),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(horizontal: 30, vertical: 12),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
),
),
),
home: const MainPage(),
);
}
}
class MainPage extends StatefulWidget {
const MainPage({super.key});
@override
State<MainPage> createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
int _currentIndex = 0;
final List<Widget> _pages = const [
HomePage(),
HealthInputPage(),
ProfilePage(),
];
void _onItemTapped(int index) {
setState(() {
_currentIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: _pages[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: _onItemTapped,
selectedItemColor: Colors.teal,
items: const [
BottomNavigationBarItem(icon: Icon(Icons.home), label: "首页"),
BottomNavigationBarItem(icon: Icon(Icons.add), label: "健康录入"),
BottomNavigationBarItem(icon: Icon(Icons.person), label: "个人中心"),
],
),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String name = "未填写";
String gender = "未填写";
String age = "未填写";
String height = "未填写";
String weight = "未填写";
String heart = "未填写";
String saveTime = "暂无记录时间";
double bmi = 0.0;
String bmiLevel = "暂无数据";
void calcBMI() {
if (height == "未填写" || weight == "未填写") {
bmi = 0.0;
bmiLevel = "暂无数据";
return;
}
double h = double.parse(height) / 100;
double w = double.parse(weight);
bmi = w / (h * h);
bmi = double.parse(bmi.toStringAsFixed(2));
if (bmi < 18.5) {
bmiLevel = "偏瘦";
} else if (bmi < 24) {
bmiLevel = "正常";
} else if (bmi < 28) {
bmiLevel = "超重";
} else {
bmiLevel = "肥胖";
}
}
Future<void> _loadData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
name = prefs.getString("name") ?? "未填写";
gender = prefs.getString("gender") ?? "未填写";
age = prefs.getString("age") ?? "未填写";
height = prefs.getString("height") ?? "未填写";
weight = prefs.getString("weight") ?? "未填写";
heart = prefs.getString("heart") ?? "未填写";
saveTime = prefs.getString("saveTime") ?? "暂无记录时间";
});
calcBMI();
}
@override
void initState() {
super.initState();
_loadData();
}
Widget _buildItem(String label, String value) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(label, style: const TextStyle(fontSize: 16)),
Text(value, style: TextStyle(fontSize: 16, color: Colors.teal[600], fontWeight: FontWeight.w500)),
],
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("首页")),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text("个人健康信息", style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold)),
const SizedBox(height: 20),
Card(
child: Padding(
padding: const EdgeInsets.all(22),
child: Column(
children: [
_buildItem("姓名", name),
_buildItem("性别", gender),
_buildItem("年龄", "$age 岁"),
_buildItem("身高", "$height cm"),
_buildItem("体重", "$weight kg"),
_buildItem("心率", "$heart 次/分"),
_buildItem("录入时间", saveTime),
],
),
),
),
const SizedBox(height: 20),
Card(
color: Colors.teal[50],
child: Padding(
padding: const EdgeInsets.all(22),
child: Column(
children: [
const Text("BMI体质指数", style: TextStyle(fontSize: 19, fontWeight: FontWeight.bold)),
const SizedBox(height: 12),
Text(bmi == 0 ? "暂无数据" : "$bmi",
style: TextStyle(fontSize: 24, color: Colors.teal[700], fontWeight: FontWeight.bold)),
const SizedBox(height: 10),
Text("健康评级:$bmiLevel", style: TextStyle(fontSize: 17)),
],
),
),
),
const SizedBox(height: 30),
Center(
child: ElevatedButton(onPressed: _loadData, child: const Text("刷新数据")),
),
],
),
),
);
}
}
class HealthInputPage extends StatefulWidget {
const HealthInputPage({super.key});
@override
State<HealthInputPage> createState() => _HealthInputPageState();
}
class _HealthInputPageState extends State<HealthInputPage> {
final TextEditingController _nameController = TextEditingController();
final TextEditingController _ageController = TextEditingController();
final TextEditingController _heightController = TextEditingController();
final TextEditingController _weightController = TextEditingController();
final TextEditingController _heartController = TextEditingController();
String _gender = "男";
// 获取当前规范时间
String _getNowTime() {
DateTime now = DateTime.now();
return "${now.year}-${now.month}-${now.day} ${now.hour}:${now.minute}";
}
Future<void> _saveData() async {
String name = _nameController.text.trim();
String ageStr = _ageController.text.trim();
String heightStr = _heightController.text.trim();
String weightStr = _weightController.text.trim();
String heartStr = _heartController.text.trim();
if (name.isEmpty || ageStr.isEmpty || heightStr.isEmpty || weightStr.isEmpty || heartStr.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("请填写完整信息")));
return;
}
int? age = int.tryParse(ageStr);
double? height = double.tryParse(heightStr);
double? weight = double.tryParse(weightStr);
int? heart = int.tryParse(heartStr);
if (age == null || age < 1 || age > 120) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("年龄需在1-120之间")));
return;
}
if (height == null || height < 50 || height > 250) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("身高需在50-250之间")));
return;
}
if (weight == null || weight < 1 || weight > 300) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("体重需在1-300之间")));
return;
}
if (heart == null || heart < 40 || heart > 180) {
ScaffoldMessenger.of(context).showSnackBar(content: Text("心率需在40-180之间"));
return;
}
String nowTime = _getNowTime();
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString("name", name);
await prefs.setString("gender", _gender);
await prefs.setString("age", ageStr);
await prefs.setString("height", heightStr);
await prefs.setString("weight", weightStr);
await prefs.setString("heart", heartStr);
await prefs.setString("saveTime", nowTime);
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("保存成功")));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("健康录入")),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text("姓名", style: TextStyle(fontSize: 16)),
SizedBox(height: 8),
TextField(
controller: _nameController,
decoration: InputDecoration(
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
contentPadding: EdgeInsets.symmetric(horizontal: 15, vertical: 12),
),
),
const SizedBox(height: 18),
const Text("性别", style: TextStyle(fontSize: 16)),
Row(
children: [
Expanded(
child: RadioListTile(
title: const Text("男"),
value: "男",
groupValue: _gender,
onChanged: (value) => setState(() => _gender = value!),
),
),
Expanded(
child: RadioListTile(
title: const Text("女"),
value: "女",
groupValue: _gender,
onChanged: (value) => setState(() => _gender = value!),
),
),
],
),
const SizedBox(height: 10),
const Text("年龄", style: TextStyle(fontSize: 16)),
SizedBox(height: 8),
TextField(
controller: _ageController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
contentPadding: EdgeInsets.symmetric(horizontal: 15, vertical: 12),
),
),
const SizedBox(height: 18),
const Text("身高(cm)", style: TextStyle(fontSize: 16)),
SizedBox(height: 8),
TextField(
controller: _heightController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
contentPadding: EdgeInsets.symmetric(horizontal: 15, vertical: 12),
),
),
const SizedBox(height: 18),
const Text("体重(kg)", style: TextStyle(fontSize: 16)),
SizedBox(height: 8),
TextField(
controller: _weightController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
contentPadding: EdgeInsets.symmetric(horizontal: 15, vertical: 12),
),
),
const SizedBox(height: 18),
const Text("心率(次/分)", style: TextStyle(fontSize: 16)),
SizedBox(height: 8),
TextField(
controller: _heartController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
contentPadding: EdgeInsets.symmetric(horizontal: 15, vertical: 12),
),
),
const SizedBox(height: 30),
Center(
child: ElevatedButton(onPressed: _saveData, child: const Text("保存数据")),
),
],
),
),
);
}
}
class ProfilePage extends StatefulWidget {
const ProfilePage({super.key});
@override
State<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
String name = "未填写";
String gender = "未填写";
String age = "未填写";
String height = "未填写";
String weight = "未填写";
String heart = "未填写";
String saveTime = "暂无记录时间";
Future<void> _loadData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
name = prefs.getString("name") ?? "未填写";
gender = prefs.getString("gender") ?? "未填写";
age = prefs.getString("age") ?? "未填写";
height = prefs.getString("height") ?? "未填写";
weight = prefs.getString("weight") ?? "未填写";
heart = prefs.getString("heart") ?? "未填写";
saveTime = prefs.getString("saveTime") ?? "暂无记录时间";
});
}
Future<void> _clearData() async {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text("确认清空"),
content: const Text("确定要清空所有数据吗?"),
actions: [
TextButton(onPressed: () => Navigator.pop(context), child: const Text("取消")),
TextButton(
onPressed: () async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.clear();
_loadData();
Navigator.pop(context);
},
child: const Text("确定", style: TextStyle(color: Colors.red)),
),
],
),
);
}
@override
void initState() {
super.initState();
_loadData();
}
Widget _buildItem(String label, String value) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(label, style: const TextStyle(fontSize: 16)),
Text(value, style: TextStyle(fontSize: 16, color: Colors.teal[600], fontWeight: FontWeight.w500)),
],
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("个人中心")),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text("我的健康信息", style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold)),
const SizedBox(height: 20),
Card(
child: Padding(
padding: const EdgeInsets.all(22),
child: Column(
children: [
_buildItem("姓名", name),
_buildItem("性别", gender),
_buildItem("年龄", "$age 岁"),
_buildItem("身高", "$height cm"),
_buildItem("体重", "$weight kg"),
_buildItem("心率", "$heart 次/分"),
_buildItem("录入时间", saveTime),
],
),
),
),
const SizedBox(height: 30),
Center(
child: ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: Colors.redAccent),
onPressed: _clearData,
child: const Text("清空所有数据"),
),
),
],
),
),
);
}
}
📱 调试与运行完整步骤
- 停止项目原有运行
- 确认依赖配置无需修改
- 修改 lib/main.dart 为 Day12 完整代码
- 终端执行 flutter pub get 同步依赖
- 连接鸿蒙模拟器,执行 flutter run
- 进入健康录入填写合法信息并保存
- 返回首页、个人中心查看自动生成的录入时间
- 点击清空数据,时间同步恢复默认提示,功能正常
🔐 跨平台适配说明
本次时间记录功能完全适配 OpenHarmony 系统,系统时间获取、格式拼接、本地持久化存储在鸿蒙端运行稳定,时间展示布局无错位、无遮挡,保留前期 UI 美化与全部业务功能兼容正常。
❌ 常见错误排查
| 错误现象 | 解决方法 |
|---|---|
| 时间不更新 | 保存数据时确认同步存入 saveTime 字段 |
| 清空后仍显示旧时间 | 清空 SharedPreferences 后重新调用加载数据方法 |
| 时间格式杂乱 | 统一按年月日时分格式手动拼接,不依赖第三方库 |
🎨 项目后续规划
Day12 已完成健康数据录入时间记录与展示,本系列基础功能开发全部完结,后续可自行拓展数据列表多条记录、历史数据查询等进阶功能。
📌 项目总结
本篇 Day12 在前期 UI 美化、BMI 计算、表单校验、本地存储基础上,新增系统时间获取与持久化记录功能,保存健康数据自动标记录入时间,在首页和个人中心同步展示,清空数据自动重置时间提示。项目从页面搭建、数据存储、表单校验、BMI 运算、UI 美化到时间记录完整闭环,功能完善、界面规整,全程适配鸿蒙跨平台运行。
✅ 结尾小贴士
- 利用 DateTime 可快速获取系统本地时间,无需引入第三方依赖
- 结合 SharedPreferences 可轻松实现时间持久化,适合各类信息录入类 App 开发参考
- 全套 Day1 至 Day12 代码可连贯使用,可直接用于学习复盘
- 点赞收藏不迷路,后续 24 天每日开发笔记持续同步更新!
更多推荐

所有评论(0)