DateTime.now()取值不更新导致Firestore评论时间戳相同问题如何解决
问题成因
你将DateTime timestamp = DateTime.now()定义在addComment函数的外部,属于父级/全局作用域变量,它只会在对应代码块初始化时执行一次生成时间值。后续不管间隔多久调用addComment发布评论,都会复用最开始生成的固定时间戳,所以出现多条评论时间一致的问题。
解决方案
提供两种可行方案,优先推荐第二种:
- 方案1:调整时间戳的作用域,将时间生成逻辑移到
addComment函数内部,每次发布评论时实时生成当前本地时间
addComment() async{ // 每次调用函数时生成最新时间 final DateTime timestamp = DateTime.now(); commentsRef.doc(postId).collection('comments').add({ 'username': current.uniqueName, 'comment': commentController.text, 'timestamp': timestamp, 'avatarUrl': current.profilePictureURL, 'userId': current.userID });}
- 方案2:使用Firestore官方提供的服务器时间戳,完全避免本地时间不准、重复的问题,由Firestore服务端收到请求时生成统一时间,更适合评论排序等业务场景
// 需确保已正常导入cloud_firestore依赖 addComment() async{ commentsRef.doc(postId).collection('comments').add({ 'username': current.uniqueName, 'comment': commentController.text, 'timestamp': FieldValue.serverTimestamp(), 'avatarUrl': current.profilePictureURL, 'userId': current.userID });}
内容的提问来源于stack exchange,提问作者Lorenzo Cutrupi
相关产品推荐
相关产品推荐

