Flutter开发中如何按指定格式向Firebase写入数据
如何在Flutter中按指定格式向Firebase写入数据
目标数据结构如下:
其中qHFij7jKyTa1t9RhkWN2LImqwVl2为User ID(用户ID),-MjYl_8EVJJkWcHgn6mJ为帖子ID。
你当前尝试使用的Flutter写入代码如下:
await _firestore .collection('Notifications') .doc(FirebaseAuth.instance.currentUser!.uid) .collection(postid) .doc() .set({ 'userid': FirebaseAuth.instance.currentUser!.uid, 'comment': 'test', 'postid': postid, 'ispost': true, 'time': DateTime.now(), });
实际运行生成的结构不符合预期:
你此前在Android原生项目中实现该逻辑的代码如下:
ref = ref.getInstance.getReference("Notifications").child(publisherid); HashMap<String, Object> hashmap = new HashMap<>(); hashmap.put("userid", userid); hashmap.put("comment", comment); hashmap.put("postid", postid); hashmap.put("ispost", true); hashmap.put("time", DateTime.now());
问题原因
- 数据库选型不匹配:Android原生代码操作的是Firebase Realtime Database(RTDB,采用JSON树结构,无强制层级要求),但Flutter代码中使用的是Cloud Firestore(采用文档-集合交替的层级结构,有严格的层级规则),二者是Firebase旗下独立的两个数据库,结构逻辑不通用。
- 路径层级错误:如果使用Firestore,你在用户UID对应的文档下,错误地将
postid变量值作为子集合名,又在该集合下额外生成了一层随机文档,导致最终结构比预期多了一层错误节点。 - 业务逻辑偏差:当前代码中通知所属的用户ID写死为当前登录用户ID,实际业务中通知应该发送给帖子作者(对应Android代码中的
publisherid),需要替换为帖子作者的UID,否则通知会写入当前用户自己的通知列表。
解决方案
方案1:完全对齐Android原生逻辑(推荐,结构完全匹配)
如果要和Android项目共用同一个数据库、生成完全一致的-MjYl开头的push ID、层级和目标示意图完全一致,直接在Flutter中接入firebase_database插件操作Realtime Database即可,写法和Android原生几乎一致:
// 获取RTDB实例,定位到对应用户的通知节点 final DatabaseReference notificationRef = FirebaseDatabase.instance .ref("Notifications/${publisherId}"); // publisherId替换为帖子作者ID // 生成和Android push()逻辑完全一致的唯一ID(即-MjYl开头的ID) final newNotification = notificationRef.push(); await newNotification.set({ 'userid': FirebaseAuth.instance.currentUser!.uid, 'comment': 'test', 'postid': postid, 'ispost': true, 'time': DateTime.now().millisecondsSinceEpoch, // RTDB不支持直接存DateTime对象,建议存时间戳 });
运行后生成的结构和目标示意图完全一致,层级为:Notifications(根节点)→ 用户ID → push生成的通知ID → 各通知字段。
方案2:继续使用Cloud Firestore
如果你确定要使用Cloud Firestore,必须遵守其「集合-文档-集合-文档」的交替层级规则,给用户文档下的通知列表加一个固定名称的子集合(比如固定命名为list,名称可自定义,必须为固定值,不能用postid变量当集合名):
await _firestore .collection('Notifications') .doc(publisherId) // 替换为帖子作者ID,不要用当前登录用户ID .collection('list') // 固定子集合名,补全Firestore要求的层级 .doc(postid) // 如果需要文档ID和帖子ID一致就传postid,需要自动生成通知ID则调用无参doc() .set({ 'userid': FirebaseAuth.instance.currentUser!.uid, 'comment': 'test', 'postid': postid, 'ispost': true, 'time': DateTime.now(), // Firestore支持直接传入DateTime,会自动转换为时间戳存储 });
注意:Firestore的强制层级规则决定了控制台中会多显示一层固定名称的子集合节点,这是Firestore的固有特性,无法去掉。如果需要完全匹配示意图的层级,请选择方案1使用Realtime Database。
内容的提问来源于stack exchange,提问作者user18124547
相关产品推荐
相关产品推荐

