firebase Flutter Firestore,检查是否存在收藏?[重复]

oymdgrw7  于 2023-01-18  发布在  Flutter
关注(0)|答案(1)|浏览(112)
    • 此问题在此处已有答案**:

In Dart/Flutter, how can I find out if there is no Collection in the Firestore database?(4个答案)
1年前关闭。
我是dart/firebase的新手,目前正在尝试使用它。我试图找出是否有方法可以发现一个集合是否存在。
我创建了一个方法,每次用户注册时,它会创建一个以他们的用户名命名的集合。每次他们登录时,"我想检查它是否存在",如果不创建它。我不想让用户登录" Jmeter 板"页面而没有集合。
我目前的编码,创建一个集合时,他们注册,也当登录在lol,不能弄清楚检查是否存在集合。
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));
  }

}
t3psigkw

t3psigkw1#

如果一个集合不存在,从技术上讲,这意味着它没有文档。你可以查询该集合,如果它有0个文档,那么这可能意味着它不存在。

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

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

相关问题