Flutter Firestore,检查集合是否存在?

Red*_*ion 1 android dart firebase flutter google-cloud-firestore

我对 dart/firebase 非常陌生,目前正在尝试它。我想弄清楚是否有办法找出集合是否存在。

我创建了一个方法,每次用户注册时,它都会创建一个以其用户 ID 命名的集合。每次他们登录时“我想检查它是否存在”,如果不存在则创建它。我不希望用户在没有集合的情况下登录“仪表板”页面。

我当前的编码,在注册时创建一个集合,并且在登录时创建一个集合,哈哈,无法弄清楚检查集合是否存在。

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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));
  }

}
Run Code Online (Sandbox Code Playgroud)

Dha*_*raj 6

如果集合不存在,从技术上讲这意味着其中没有文档。您可以查询该集合,如果其中有 0 个文档,则可能意味着它不存在。

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

它将.limit(1)仅从该集合中获取一份文档(如果存在),因此这一点很重要,否则您最终将读取其中的所有文档。