'Flutter Firebase: How do I only record the first name of a display name in Firestore?
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!
Solution 1:[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);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Adrian Mole |
