0

我将以下代码写入 Firestore,用于使用 Google 登录的身份验证类:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';

class AuthService {
  final GoogleSignIn _googleSignIn = GoogleSignIn();
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final Firestore _db = Firestore.instance;


  Future<FirebaseUser> get getUser => _auth.currentUser();

  Stream<FirebaseUser> get user => _auth.onAuthStateChanged;

  Future<FirebaseUser> googleSignIn() async {
    try {
      GoogleSignInAccount googleSignInAccount = await _googleSignIn.signIn();
      GoogleSignInAuthentication googleAuth =
          await googleSignInAccount.authentication;

      final AuthCredential credential = GoogleAuthProvider.getCredential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      FirebaseUser user = (await _auth.signInWithCredential(credential)).user;
      updateUserData(user);

    Future<void> updateUserData(FirebaseUser user) {
    DocumentReference usersRef = _db.collection('users').document(user.uid);

    return usersRef.setData({
      'uid': user.uid,
      'email': user.email,
      'displayName': user.displayName,
      'photoUrl': user.photoUrl,
      'lastActivity': DateTime.now(),
    }, merge: true);

  }

  Future<void> signOut() {
    return _auth.signOut();
  }

}

我只需要将名字收集到 Firestore。有没有一种合乎逻辑的方式可以在我的身份验证过程中做到这一点?谢谢!

4

0 回答 0