I'm using the firebase_ui_auth package to control auth and my ProfileScreen.
I'm building a Flutter app using Firestore/Firebase Auth. When the user account is created I have a Cloud Function trigger to create a user document users/${uid}
.
What I want to happen is when a user updates their Display Name that the update syncs with Firestore. I have a Provider (Riverpod) that listens to AuthStateChanges
, however, updating a user doesn't trigger that.
There are no Cloud Functions for this kind of trigger.
How can I listen for these kinds of changes (and get the actual change)? I can easily update Firestore once I understand where to listen for changes
You can use userChanges method which will listen for any changes in user profile, So you can update the displayName accordingly as follows :
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
void listenForUserProfileChanges() {
FirebaseAuth.instance.userChanges().listen((User? user) async {
if (user != null) {
String newDisplayName = user.displayName ?? '';
String uid = user.uid;
try {
// Update the displayName in the Firestore document
await FirebaseFirestore.instance
.collection('users')
.doc(uid)
.update({'displayName': newDisplayName});
print('DisplayName updated successfully in Firestore document.');
} catch (error) {
print('Error updating DisplayName in Firestore: $error');
}
print('User $uid updated their displayName to $newDisplayName');
} else {
print('User is null');
}
});
}
void main() {
listenForUserProfileChanges();
}
I have wrapped this into a function but you can specify anywhere in your application.
Reference : userChanges method