I’m building an app in Flutter that uses Cloud Firestore to store user records. I also want to save the application settings to Cloud Firestore. For example, the application will use several design templates to choose from. Data about the current topic is written in the database.
The presented code works well with a collection that already exists in Cloud Firestore. When the application starts, the appropriate collection is checked and UserPreferencesManager() is called if data is available. But what to do when you first launch the application, when such a collection does not yet exist in the database? How do I go to PageForNewUser() where this collection will be created? The above code does not cope with this task.
How can I write a query to check if a collection is missing from the database? Or maybe there is a method to check if the logged-in user is a new user without any entries in the database.
Here is my code:
class CheckingUserStatus extends StatefulWidget {
const CheckingUserStatus({super.key});
@override
State<CheckingUserStatus> createState() => _CheckingUserStatusState();
}
class _CheckingUserStatusState extends State<CheckingUserStatus> {
final String? _email = FirebaseAuth.instance.currentUser?.email; //Получаем email текущего пользователя
@override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder(
stream: FirebaseFirestore.instance.collection('$_email data').doc('data').collection('currentTemplate').snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
}
else if (snapshot.hasData) {
return const UserPreferencesManager();
}
else { return const PageForNewUser();}
return const Center(child: CircularProgressIndicator());
},
),
);
}
}
2
Answers
Try to Write An Function called
doesCollectionExist
And Call This
There is no query present that can help you check if a collection is missing. However, you can create a query that should return documents from the collection and add a
limit(1)
call. If you get a document, then the collection exists, otherwise it doesn’t exist. Alternatively, you can count the documents.