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

Flutter中Firebase Firestore的set()方法无法正常工作

问题:Firestore set方法添加文档无反应

我尝试使用set方法向Firestore数据库添加新文档时,没有任何反应。

Future<void> _createUser() async {
    try {
      await Auth().createUserWithEmailAndPassowrd(
        email: _emailController.text,
        password: _passwordController.text,
      );

      final newUser = UserData(
        name: '',
        dateOfBirth: DateTime.now(),
        sex: false,
        location: GeoPoint(0, 0),
        bio: '',
        sportsPlayed: Map(),
        hasSetupAccount: false,
        // profileImage: null,
      );

      final json = newUser.toJson();
      FirebaseFirestore.instance
          .collection('Users')
          .doc(Auth().currentUser!.uid.toString())
          .set(json);
解决方案
  • 未等待set操作完成:代码中调用set(json)时没有添加await,操作可能还没执行完方法就结束了,导致无反应。修改为:

    await FirebaseFirestore.instance
        .collection('Users')
        .doc(Auth().currentUser!.uid.toString())
        .set(json);
    
  • 错误捕获范围不足:当前try块仅包裹了注册逻辑,set操作的错误无法被捕获,即使出错也看不到提示。将set操作移入try块,并添加catch分支:

    try {
      await Auth().createUserWithEmailAndPassowrd(
        email: _emailController.text,
        password: _passwordController.text,
      );
    
      final newUser = UserData(
        name: '',
        dateOfBirth: DateTime.now(),
        sex: false,
        location: GeoPoint(0, 0),
        bio: '',
        sportsPlayed: Map(),
        hasSetupAccount: false,
        // profileImage: null,
      );
    
      final json = newUser.toJson();
      await FirebaseFirestore.instance
          .collection('Users')
          .doc(Auth().currentUser!.uid.toString())
          .set(json);
    } catch (e) {
      print('操作失败:$e');
      // 可在此处添加用户可见的错误提示
    }
    
  • currentUser可能未及时更新:注册完成后Auth().currentUser可能还未同步更新,强制解包可能引发问题。建议使用注册方法返回的用户凭证获取uid:

    final userCredential = await Auth().createUserWithEmailAndPassowrd(
      email: _emailController.text,
      password: _passwordController.text,
    );
    final uid = userCredential.user!.uid;
    await FirebaseFirestore.instance
        .collection('Users')
        .doc(uid)
        .set(json);
    
  • 检查Firestore权限规则:若权限规则不允许写入,也会导致操作无响应。确保已认证用户有权限写入对应文档,示例规则:

    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /Users/{userId} {
          allow read, write: if request.auth != null && request.auth.uid == userId;
        }
      }
    }
    

内容的提问来源于stack exchange,提问作者Jaime Ferreira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 04:45:36