如何在Firestore中读写Flutter的TimeOfDay值?
在Firestore中读写Flutter的TimeOfDay值
TimeOfDay本身无法直接序列化存储到Firestore,需要转换成Firestore支持的数据类型。你提到的"13:30"格式字符串是可行方案之一,另外还有更适合计算的整数分钟数方案,两种都能满足「与日期、时区无关」的需求,具体选哪种看你的业务场景:
方案1:转换为"HH:mm"格式字符串
这种方式直观易读,适合需要直接查看时间值的场景。
写入Firestore
// 假设已获取TimeOfDay实例 TimeOfDay selectedTime = TimeOfDay(hour: 13, minute: 30); // 格式化为两位小时+两位分钟的字符串 String timeStr = "${selectedTime.hour.toString().padLeft(2, '0')}:${selectedTime.minute.toString().padLeft(2, '0')}"; // 写入Firestore文档 await FirebaseFirestore.instance.collection('records').doc('user1').set({ 'remind_time': timeStr, });
从Firestore读取
DocumentSnapshot doc = await FirebaseFirestore.instance.collection('records').doc('user1').get(); String timeStr = doc['remind_time']; List<String> timeParts = timeStr.split(':'); TimeOfDay time = TimeOfDay(hour: int.parse(timeParts[0]), minute: int.parse(timeParts[1]));
方案2:转换为当日总分钟数(整数)
这种方式存储更高效,适合需要做时间比较、计算的场景(比如判断两个时间谁更早)。
写入Firestore
TimeOfDay selectedTime = TimeOfDay(hour: 13, minute: 30); int totalMinutes = selectedTime.hour * 60 + selectedTime.minute; await FirebaseFirestore.instance.collection('records').doc('user1').set({ 'remind_time': totalMinutes, });
从Firestore读取
DocumentSnapshot doc = await FirebaseFirestore.instance.collection('records').doc('user1').get(); int totalMinutes = doc['remind_time']; TimeOfDay time = TimeOfDay(hour: totalMinutes ~/ 60, minute: totalMinutes % 60);
方案对比
- 字符串格式:优点是直观可读,适合展示或手动编辑场景;缺点是做时间比较时需要先转成数值,步骤稍繁琐。
- 整数分钟数:优点是存储体积小,时间计算、比较效率更高;缺点是无法直接看出具体时间,可读性弱。
内容的提问来源于stack exchange,提问作者user6097845
相关产品推荐
相关产品推荐

