skip to Main Content

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


  1. Try to Write An Function called doesCollectionExist

    Future<bool> doesCollectionExist(String collectionName) async {
      // Reference to the Firestore database
      final firestoreInstance = FirebaseFirestore.instance;
    
      // Query the specified collection
      QuerySnapshot collection = await firestoreInstance.collection(collectionName).get();
    
      // Check if the collection is empty
      return collection.docs.isNotEmpty;
    }
    

    And Call This

    bool collectionExists = await doesCollectionExist('your_collection_name');
    
    if (collectionExists) {
      print('The collection exists.');
    } else {
      print('The collection does not exist.');
    }
    
    Login or Signup to reply.
  2. How can I write a query to check if a collection is missing from the database?

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search