0

I have the following code writing to Firestore for an auth class with Google Sign in:

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

}

I need to only collect the first name to Firestore. Is there a logical way that I can do it within my auth process? Thanks!

DB Cooper
  • 63
  • 1
  • 9

2 Answers2

1

You can use the string spilt() function as follows:

  Future<void> updateUserData(FirebaseUser user) {
    DocumentReference usersRef = _db.collection('users').document(user.uid);
    List<String> spiltName =value.user!.displayName!.split(" ");
    return usersRef.setData({
      'uid': user.uid,
      'email': user.email,
      'displayName': spilName.first, 
      'photoUrl': user.photoUrl,
      'lastActivity': DateTime.now(),
    }, merge: true);

  }
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
0

There's no way to identify the first name of the user's displayName from GoogleSignIn. User first names could possibly consist of two or three names. If you're considering the first name from the displayName to be its 'first name', then you can split on the displayName and fetch its first index.

user.displayName.split(' ')[0];

Note that it's possible for displayName to return null. What you can do here is prompt the user to update their displayName and pass the String to user.updateDisplayName(displayName)

Omatt
  • 8,564
  • 2
  • 42
  • 144