Firestore won’t create documents in the database (as part of account creation), but only sometimes

I have a Flutter application with a sign-up process, all managed by Firebase. During that process, a document for each user should be created in my Firestore database, in a users collection. I’m running a pilot program for my app. From that program, for about 1/3 of the users, a document is not created in Firestore during account creation. I have not been able to replicate this error with the production code – every time I create a new account, it works just fine. I don’t know whether I’m noticing false trends, but I’m on the West Coast and feel that a good amount of people for whom this problem occurred were on the East Coast. Just today, I had one new user who encountered this error while creating an account, and one who did not. Here are relevant parts of my code:

// This class manages navigation after verified user logs in or a new user verifies their email
class AppNav extends StatefulWidget {
  const AppNav({super.key, required this.newUser});
  final bool newUser;

  @override
  State<AppNav> createState() => _AppNavState();
}

class _AppNavState extends State<AppNav> {
  late Future<List<dynamic>> _future;
  // An initState() is used so these methods are not called multiple times
  @override
  void initState() {
    super.initState();
    Future<List<dynamic>> initApp() async {
      await FirebaseAuth.instance.currentUser!.reload();
      await context.read<MyAppState>().readHintPages();
      if (widget.newUser) {
        await context.read<MyAppState>().createUserInDB();
      }
      await context.read<MyAppState>().readUser();

      context.read<MyAppState>().navigateTo(0);
      return Future.value([]);
    }

    _future = initApp();
  }

  @override
  Widget build(BuildContext context) {
    // The asynchronous methods are called here
    // Then, once the user and app are set up, the app navigates to the home page
    return FutureBuilder(
      future: _future,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return ErrorPage(error: snapshot.error);
        } else if (snapshot.connectionState == ConnectionState.waiting) {
          return animatedLogo(context, true);
        } else {
          return MyHomePage(
            newUser: widget.newUser,
            title: '5 Minute संस्कृतम् ।',
          );
        }
      },
    );
  }
}

In another file, in a ChangeNotifier class:

  // This method creates a user document in the database with the user name
  // Errors from this method are handled in the parent widget
  Future createUserInDB() async {
    final userRef = FirebaseFirestore.instance.collection('users').doc(
          FirebaseAuth.instance.currentUser!.email!,
        );
    try {
      await userRef.set({
        'name': appUser.name,
        'quizStates': {},
        'lbPoints': 0,
        'seshHistory': {},
        'code': 'choose',
      });
      return Future.value();
    } catch (error) {
      return Future.error('(From createUserInDB) $error');
    }
  }

  // This method retrieves user data from the Firebase Firestore database
  // Errors from this method are handled in the parent widget
  Future readUser() async {
    final usersRef = FirebaseFirestore.instance.collection('users');

    try {
      QuerySnapshot<Map<String, dynamic>> usersSnapshot = await usersRef.get();
      lbUsers = [];

      // Each user document is iterated through and processed
      for (var doc in usersSnapshot.docs) {
        Map<String, dynamic> userMap = doc.data();

        // Check if this is the current user's document, and process if so
        if (doc.id == FirebaseAuth.instance.currentUser!.email!) {
          String code = userMap['code'];
          await readQuizzes(code);
          appUser = AppUser.fromMap(userMap);

          // Here, the current user's quiz data is retrieved
          for (Quiz quiz in quizzes) {
            Map<String, dynamic>? quizState = appUser.quizStates[quiz.name];
            if (quizState != null) {
              quiz.readFromState(quizState);
            }
          }
          updateMasteredQuizzes();
          // Otherwise, add user as a leaderboard user with limited points
        } else {
          lbUsers.add(LeaderboardUser.fromMap(userMap));
        }
      }
      return Future.value(appUser);
    } catch (error) {
      return Future.error('(From readUser) $error');
    }
  }

  // This method retrieves quiz data from the Firebase Firestore database
  // Errors from this method are handled in the parent widget
  Future readQuizzes(String code) async {
    try {
      // This snapshot is of the entire quiz collection
      var quizRef = FirebaseFirestore.instance.collection('quizzes');
      if (code == 'choose') {
        quizRef = quizRef.doc('Demo Quizzes').collection('all');
      } else {
        quizRef = quizRef.doc('Pilot Program').collection(code);
      }

      QuerySnapshot<Map<String, dynamic>> value = await quizRef.get();

      // Reset values before retrieving data from new account
      quizzes = [];
      masteredQuizzes = [];
      masteredQuizPoints = 0;
      currentQuiz = -1;
      currentQuizName = "";

      // Here, each quiz is added if it is to be shown
      for (DocumentSnapshot<Map<String, dynamic>> doc in value.docs) {
        Map<String, dynamic> quizMap = doc.data()!;
        Quiz quiz = Quiz.fromMap(quizMap);
        if (quiz.show && DateTime.now().isAfter(quiz.start)) {
          quizzes.add(quiz);
        }
      }

      await Future.delayed(const Duration(seconds: 4), () {});
      return Future.value(quizzes);
    } catch (error) {
      return Future.error('(From readQuizzes) $error');
    }
  }

As noticed, the app does require email verification, but all users who encounter this error notice it after verifying their account (they are taken form the verify email page to the home page, but the home page is blank because of no document in Firestore.

And if relevant at all, here are my Firestore rules:

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    // Allow read access to any authenticated user
    match /{document=**} {
      allow read: if request.auth != null;
      
    // Allow full write access to the database only for the admin user
    allow write: if request.auth.token.email == '[email protected]';
    }

    // Allow write access to the "users" collection only if the document ID matches the user's email
    match /users/{userEmail} {
      allow write: if request.auth != null && request.auth.token.email == userEmail;
      
      
    }
  }
}

I was only able to fully recreate this error by removing both the readUser() and createUserInDB() calls in the AuthFlow class. From this, I’m guessing that none of the Firestore methods in the initApp() Future method are properly completed. I’ve tweaked my code a couple of times to fix this error. For example, previously, instead of an initApp() method, I had a list of Futures in a Future.wait() with all those method calls. The user reload before all the calls in initApp() is also new, but neither of those have helped.

You may want to consider to using a Cloud Function to create that document in Firestore. Such a Cloud Function can trigger on the user-creation in Firebase Authentication, and will be much more reliable than doing this in the front-end application code.

Recognized by Google Cloud Collective

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật