【问题标题】:Flutter Firestore, Check if collection exists? [duplicate]Flutter Firestore,检查集合是否存在? [复制]
【发布时间】:2021-09-15 08:48:41
【问题描述】:

我对 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;
  }
}

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

}

【问题讨论】:

    标签: android firebase flutter dart google-cloud-firestore


    【解决方案1】:

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

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

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

    【讨论】:

    • 感谢@Dharmaraj,设法将其实施到我的项目中。
    猜你喜欢
    • 1970-01-01
    • 2021-12-22
    • 2020-08-11
    • 2019-04-19
    • 2021-01-29
    • 2019-01-21
    • 1970-01-01
    • 2020-11-17
    • 2018-12-09
    相关资源
    最近更新 更多