You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中Firebase Firestore无法创建子集合及文档求助

解决Firestore未创建集合/文档的问题

问题原因

你当前的代码只是构建了Firestore文档的引用对象,并没有执行实际的写入操作。Firestore不会因为你创建了引用就自动生成集合或文档,必须调用写入方法(如set()/add())才会在云端创建对应的数据结构。

另外还有一个潜在问题:FirebaseAuth.instance.currentUser!.toString()获取的不是用户ID,而是用户对象的字符串描述(格式类似User(uid: xxx, email: xxx)),正确的用户ID应该用currentUser!.uid。

修正方案

方案1:创建指定ID的文档(用用户UID作为文档ID)

调用set()方法写入数据,即使是空对象也能触发文档和集合的创建:

void crearWorkerColeccion(String iddeldocumento) {
  print('DENTRO ${iddeldocumento}');
  // 先检查用户是否登录,避免空指针异常
  final currentUser = FirebaseAuth.instance.currentUser;
  if (currentUser == null) {
    print('错误:用户未登录');
    return;
  }

  FirebaseFirestore.instance
      .collection('Company')
      .doc('kGCOpHgRyiIYLr4Fwuys')
      .collection('WorkingDays')
      .doc(iddeldocumento)
      .collection('trabajadores') // 若要改成workers,直接替换为'workers'即可
      .doc(currentUser.uid) // 使用用户UID作为文档ID
      .set({
        // 可添加自定义字段,比如创建时间
        'createdAt': FieldValue.serverTimestamp(),
        // 其他字段如邮箱、用户名等
        'email': currentUser.email,
      })
      .then((_) => print('Worker文档创建成功'))
      .catchError((err) => print('创建失败:$err'));
}

方案2:让Firestore自动生成文档ID

如果不需要指定文档ID,使用add()方法,Firestore会自动生成唯一ID:

void crearWorkerColeccion(String iddeldocumento) {
  print('DENTRO ${iddeldocumento}');
  final currentUser = FirebaseAuth.instance.currentUser;
  if (currentUser == null) {
    print('错误:用户未登录');
    return;
  }

  FirebaseFirestore.instance
      .collection('Company')
      .doc('kGCOpHgRyiIYLr4Fwuys')
      .collection('WorkingDays')
      .doc(iddeldocumento)
      .collection('trabajadores') // 替换为'workers'如果需要
      .add({
        'userId': currentUser.uid,
        'createdAt': FieldValue.serverTimestamp(),
        'email': currentUser.email,
      })
      .then((docRef) => print('文档创建成功,ID:${docRef.id}'))
      .catchError((err) => print('创建失败:$err'));
}

关键注意事项

  • 必须调用set()或add()这类写入方法,才能在Firestore中实际创建集合和文档
  • 始终检查currentUser是否为null,避免因用户未登录导致的空指针异常
  • 不要用currentUser.toString()获取用户ID,正确的用户ID是currentUser.uid

内容的提问来源于stack exchange,提问作者Marina Fuentes Ferrero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 04:05:15