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.
2