1

im very new to dart/firebase and im currently experimenting with it. Im trying to figure out if theres a way to find out if a collection exists or not.

Ive created a method where everytime a user registers, it creates a collection named after their userid. And everytime they sign in "I want to check if it exists", if not create it. I dont want a user who signs in the 'dashboard' page without having a collection.

My current coding, creates a collection when they register, and also when the sign in lol, cant figure out to check if collection exists.

auth.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'database.dart';

class Authentication {

  static Future<User?> signInUsingEmailPassword({
    required String email,
    required String password,
    required BuildContext context,
  }) async {
    FirebaseAuth auth = FirebaseAuth.instance;
    User? user;

    try {
      UserCredential userCredential = await auth.signInWithEmailAndPassword(
        email: email,
        password: password,
      );
      user = userCredential.user;

      // Create User Database file
      await Database.createUserDataFile(
        uid: user!.uid,
        surname: 'surname',
        mobile: 12345,
      );
      // Creates User Database

    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        print('No user found for that email.');
      } else if (e.code == 'wrong-password') {
        print('Wrong password provided.');
      }
    }

    return user;
  }

  static Future<User?> registerUsingEmailPassword({
    required String name,
    required String email,
    required String password,
    required BuildContext context,
  }) async {
    FirebaseAuth auth = FirebaseAuth.instance;
    User? user;

    try {
      UserCredential userCredential = await auth.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );

      user = userCredential.user;

      // Create User Database file
      await Database.createUserDataFile(
        uid: user!.uid,
        surname: 'surname',
        mobile: 12345,
      );
      // Creates User Database

      await user.updateDisplayName(name);
      await user.reload();
      user = auth.currentUser;
    } on FirebaseAuthException catch (e) {
      if (e.code == 'weak-password') {
        print('The password provided is too weak.');
      } else if (e.code == 'email-already-in-use') {
        print('The account already exists for that email.');
      }
    } catch (e) {
      print(e);
    }

    return user;
  }

  static Future<User?> refreshUser(User user) async {
    FirebaseAuth auth = FirebaseAuth.instance;

    await user.reload();
    User? refreshedUser = auth.currentUser;

    return refreshedUser;
  }
}

database.dart

import 'package:cloud_firestore/cloud_firestore.dart';

final FirebaseFirestore _firestore = FirebaseFirestore.instance;
// Database Collection Name
final CollectionReference _mainCollection = _firestore.collection('_TestFB');

class Database {
  static String? userUid;

  // Create User Data File
  static Future<void> createUserDataFile({
    required String uid,
    required String surname,
    required int mobile,
  }) async {
    // - Col:_TestFB/Doc:UserData/Col:profile/
    DocumentReference documentReferencer =
        _mainCollection.doc('UserData').collection(uid).doc('Profile');
    Map<String, dynamic> data = <String, dynamic>{
      "surname": surname,
      "mobile": mobile,
    };

    // Check if user Exists
    //print('users exists?');
  
    //
    await documentReferencer
        .set(data)
        .whenComplete(() => print("UserData Profile Created for -- " + uid))
        .catchError((e) => print(e));
  }

}
RedsVision
  • 33
  • 7

1 Answers1

6

If a collection doesn't exist, that technically means there are no documents in it. You can query for that collection and if it has 0 documents in it then that could mean it's absent.

FirebaseFirestore.instance
  .collection('colName')
  .limit(1)
  .get()
  .then((checkSnapshot) {
    if (checkSnapshot.size == 0) {
      print("Collection Absent");
    } 
  });

The .limit(1)will fetch only one document from that collection if exists so that's important or you'll end up reading all the documents from it.

Muhammad Vaid
  • 125
  • 2
  • 9
Dharmaraj
  • 47,845
  • 8
  • 52
  • 84