簡體   English   中英

如何同步Firestore數據庫和Firebase認證

[英]How to sync Firestore database and Firebase Authentication

我正在嘗試使用 flutter 創建一個簡單的銀行應用程序。我正在自己創建用戶登錄信息並嘗試使用 firebase 對其進行身份驗證。我已經對應用程序的身份驗證部分進行了編碼。這是代碼:

import 'package:banking_app_firebase/screens/customers_info.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';

import '../constants.dart';

class LoginScreen extends StatefulWidget {
  static const String id = 'login_screen';
  const LoginScreen({Key? key}) : super(key: key);

  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _auth = FirebaseAuth.instance;
  bool showSpinner = false;
  String? email;
  String? password;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: ModalProgressHUD(
        inAsyncCall: showSpinner,
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Flexible(
                child: Hero(
                  tag: 'logo',
                  child: Container(
                    height: 100,
                    child: Image.network(
                      "https://image.flaticon.com/icons/png/512/662/662622.png",
                    ),
                  ),
                ),
              ),
              SizedBox(height: 20),
              TextField(
                keyboardType: TextInputType.emailAddress,
                textAlign: TextAlign.center,
                onChanged: (value) {
                  email = value;
                },
                decoration:
                    kTextFieldDecoration.copyWith(hintText: 'Enter your email'),
              ),
              SizedBox(
                height: 20,
              ),
              TextField(
                obscureText: true,
                textAlign: TextAlign.center,
                onChanged: (value) {
                  password = value;
                },
                decoration: kTextFieldDecoration.copyWith(
                    hintText: "Enter your password"),
              ),
              SizedBox(
                height: 24,
              ),
              Padding(
                padding: EdgeInsets.symmetric(vertical: 16),
                child: Material(
                  elevation: 5,
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(30),
                  child: MaterialButton(
                    onPressed: () async {
                      setState(() {
                        showSpinner = true;
                      });
                      try {
                        final user = await _auth.signInWithEmailAndPassword(
                            email: email!, password: password!);
                        if (user != null) {
                          Navigator.pushNamed(context, CustomerScreen.id);
                        }
                        setState(() {
                          showSpinner = true;
                        });
                      } catch (e) {
                        print(e);
                      }
                    },
                    height: 42,
                    child: Text(
                      "Login",
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
    ;
  }
}

示例用戶:

在此處輸入圖像描述

但是,我不知道如何將這些信息與我的數據庫同步,以便我可以訪問數據庫中的數據。 這是我的示例數據庫:

在此處輸入圖像描述

認證成功后如何獲取客戶的姓名、余額等信息? 我的意思是,我怎么知道 Firebase、身份驗證 email 和密碼與 firestore 數據庫相同?

認證成功后如何獲取客戶的姓名、余額等信息?

我知道您想將customers集合的一個文檔鏈接到每個用戶。 這樣做的經典解決方案是使用用戶uid作為 Firestore 文檔 ID。

一旦創建了用戶,您就可以獲取其uid並創建 Firestore 文檔,例如:

final user = await _auth.signInWithEmailAndPassword(
        email: email!, password: password!
);
if (user != null) {
    await addCustomer(user.uid, email, password);
    Navigator.pushNamed(context, CustomerScreen.id);
}


...


CollectionReference customers = FirebaseFirestore.instance.collection('customers');

Future<void> addCustomer(userID, email, password) {
  return customers
    .doc(userID)
    .set({
      ...
    })
    .then((value) => print("Customer added"))
    .catchError((error) => print("Failed to add customer: $error"));
}

我從您下面的評論中了解到,您想查詢customers集合以查找具有特定 email 和密碼的用戶。

這可以通過查詢實現,但是我建議不要使用密碼值來執行查詢。 這是您應避免用作查詢參數的敏感數據。

實際上你可以很好地查詢 email:因為你不能用相同的 email 創建兩個 Firebase 用戶,你確信你的查詢將返回一個唯一的結果(如果你沒有在customers集合中創建一些重復的文檔...... ).

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM