User displayName returns null in Firebase Auth - firebase

I want to add a user's DisplayName upon creating a new user. When I tried to use updateProfile method, it gives below warning
/// Updates a user's profile data.
#Deprecated(
'Will be removed in version 2.0.0. '
'Use updatePhotoURL and updateDisplayName instead.',
How can get around this ??
String email, String password) async {
final UserCredential userCredential =
await _firebaseAuth.createUserWithEmailAndPassword(
email: email.trim(), password: password.trim());
await userCredential.user.updateDisplayName('Mohamed Rahuman');
User user = userCredential.user;
print(user);
return _userFromFirebaseUser(user);
}
flutter: User(displayName: null, email: test1#gmail.com, emailVerified: false, isAnonymous: false, metadata: UserMetadata(creationTime: 2021-06-06 10:35:13.689, lastSignInTime: 2021-06-06 10:35:13.689), phoneNumber: null, photoURL: null, providerData, [UserInfo(displayName: null, email: test1#gmail.com, phoneNumber: null, photoURL: null, providerId: password, uid: test1#gmail.com)], refreshToken: , tenantId: null, uid: gghhhhhhhh55555666)
THIS IS FIXED: with firebase_auth 1.3.0 (see the Changelog)

Had the same issue. Solved by calling:
await user.reload();
user = await _auth.currentUser;
this is the full code snippet:
UserCredential result = await _auth.createUserWithEmailAndPassword(
email: email, password: password);
User? user = result.user;
if (user != null) {
//add display name for just created user
user.updateDisplayName(displayName);
//get updated user
await user.reload();
user = await _auth.currentUser;
//print final version to console
print("Registered user:");
print(user);
}

I had the same issue in my signup function while updating (updatePhotoURL)
You need to update your user by
ourUser = FirebaseAuth.instance.currentUser;
await ourUser!.updatePhotoURL(defaultProfileImage);
await ourUser!.displayName(userName);
Check how I did it
Future register(
String email,
String password,
String? name,
String? mob,
String? description,
//DateTime? signUPDate,
) async {
setIsLoading(true);
try {
UserCredential authResult = await _firebaseAuth
.createUserWithEmailAndPassword(email: email, password: password,);
ourUser = authResult.user;
setIsLoading(false);
//create new doc for the user with his unique uid
await UserDatabaseServices(uid: ourUser!.uid)
.addUserData(ourUser!.uid,email,password,name,mob,description,currentTime);
ourUser = _firebaseAuth.currentUser;
await ourUser!.updatePhotoURL(defaultProfileImage);
notifyListeners();
return ourUser;
} on SocketException {
setIsLoading(false);
setMessage('No internet');
} on FirebaseAuthException catch (e) {
setIsLoading(false);
setMessage(e.message);
}
}

The cause of this issue was displayName and photoURL is unable to be set to null. More details are discussed here. As you've mentioned, this issue should be fixed as of version 1.3.0.
To fetch the display name configured during Registration, you can fetch by calling currentUser on your FirebaseAuth instance.
var currentUser = FirebaseAuth.instance.currentUser;
debugPrint('${currentUser.displayName}');

Related

How to get the UID Authentication from Firebase in Flutter and save in Firestore

I'm trying to get the uid, but it always returns the uid of the previously created account.
createUserWithEmailAndPassword does not execute the login after being completed.
So it should be returning the uid correctly, right?
Below are 2 pictures of the database and Authentication, as well as the code.
Future _singUp() async {
final User? user = auth.currentUser;
final uid = user!.uid;
try {
await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
);
await FirebaseFirestore.instance.collection('users').add({
'email': _emailController.text,
'name': _nameController.text,
'Id_usuario': uid
});
} on FirebaseAuthException catch (e) {
_handleSingUpError(e);
}
}
When you use createUserWithEmailAndPassword it will return a UserCredential as a result, you can use that to update your user variable, so in code it would be something like this:
UserCredential result = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: email, password: password);
User? user = result.user;

Firebase authenthication

Im trying to use firebase for my flutter apps, and its seem there is an error in my code , i know firebaseuser need to change to user, but its seem it does not work , please help me , im new.
import 'package:firebase_auth/firebase_auth.dart';
import 'package:quizmaker/view/signin.dart';
import 'package:quizmaker/models/user.dart';
class AuthService {
FirebaseAuth _auth = FirebaseAuth.instance;
Future signInEmailAndPass(String email, String password) async {
try {
UserCredential userCredential = await _auth.signInWithEmailAndPassword(
email: email, password: password);
User user = authResult.user; //the error is in this part
} catch (e) {
print(e.toString());
}
}
}
In this code snippet:
UserCredential userCredential = await _auth.signInWithEmailAndPassword(
email: email, password: password);
User user = authResult.user;
You're trying to use an authResult variable that is never defined. My best guess is that you want to get the user from the userCredential instead, so:
UserCredential userCredential = await _auth.signInWithEmailAndPassword(
email: email, password: password);
User user = userCredential.user;
This still won't work though, since userCredential.user may be null, and is thus defined as User? and not User. Since you're using await, you can be certain that there is a user, so you can do:
User user = userCredential.user!;

Avoid user Login with Firebase on Creation [duplicate]

This question already has an answer here:
Flutter - remove auto login after registration in Firebase
(1 answer)
Closed 1 year ago.
I have an app where users are supposed to be created only by Admin User's the problem is that when a new user is created in Firebase the app sign's in with the new user information, so the original logged user (Admin User), has to logged out, and log back in to create a new user.
This is my function to create a new User:
void createUser(
String email,
String password,
String nombre,
String dui,
DateTime fechaNacimiento,
String telefono,
String nombreContacto,
String telefonoContacto,
DateTime fechaIngreso,
String radio,
File foto,
String acceso,
) async {
try {
final auth = FirebaseAuth.instance;
UserCredential authResult = await auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
//var uploadUid = authResult.user?.uid;
final ref = FirebaseStorage.instance
.ref()
.child('user_images')
.child(authResult.user!.uid + '.jpg');
await ref.putFile(foto);
final url = await ref.getDownloadURL();
await FirebaseFirestore.instance
.collection('users')
.doc(authResult.user!.uid)
.set({
'nombre': nombre,
'dui': dui,
'fechaNacimiento': fechaNacimiento,
'telefono': telefono,
'nombreContacto': nombreContacto,
'telefonoContact': telefonoContacto,
'fechaIngreso': fechaIngreso,
'radio': radio,
'foto': url,
'acceso': acceso,
'uid': authResult.user!.uid,
'correo': email,
'contrasena': password,
});
} catch (err) {
print(err);
}
}
Any Ideas on what to do to avoid the log in on user creation of the newly created user.
Kind Regards
The original admin user does not have to be logged out to create a new user. Simply do this.
FirebaseApp secondaryApp = await Firebase.initializeApp(
name: 'SecondaryApp',
options: Firebase.app().options,
);
try {
UserCredential credential = await FirebaseAuth.instanceFor(app: secondaryApp)
.createUserWithEmailAndPassword(
email: 'email',
password: 'password',
);
if (credential.user == null) throw 'An error occured. Please try again.';
await credential.user.sendEmailVerification();
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
return _showError('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
return _showError('An account already exists for this email.');
}
} catch (e) {
return _showError('An error occured. Please try again.');
}
...
// after creating the account, delete the secondary app as below:
await secondaryApp.delete();
The above code will not logout the admin user, the admin user can still continue with normal operations after creating the account.

Write to Firebase Firestore denied - Flutter

I am trying to save the users who sign in in the firebase database.
this is the function which is used to update the signed in user in the firebase, the fuction uses a uid to create a document with this id :
final Firestore _db = Firestore.instance;
void upadteUserData(FirebaseUser user) async {
DocumentReference ref = _db.collection("users").document(user.uid);
print("in update");
return ref.setData({
"uid": user.uid,
'email': user.email,
'displayName': user.displayName,
//'emergency': []
}, merge: true);
}
and here is the sign in fuction:
Future signInWithEmailAndPassword(String email, String password) async {
try {
AuthResult result = await _auth.signInWithEmailAndPassword(
email: email, password: password);
FirebaseUser user = result.user;
upadteUserData(user);
print("signing in");
print(result.user.email);
return _userFromFirebaseUser(user);
} catch (e) {
print(e.toString());
return null;
}
}
here's the console after signing in
I tried it twice and it was working perfectly fine 3 weeks ago. However, when I try to sign in today with different e-mails, it did not update the fire base. Any idea?

how to extract the contents of the array?

I'm writing an application on flutter and I'm a bit stuck at the moment of extracting the contents of firebase classes. How do I extract the contents of the PhoneNumber variable from "user"? I will need the extracted number to send to the server
This is the output of the debugPrint('user: $user'):
user: FirebaseUser({uid: hGLEDW6OT5ZMhWra9L4p6bB4Pw92, isAnonymous: false, phoneNumber: +79644054946, providerData: [{uid: hGLEDW6OT5ZMhWra9L4p6bB4Pw92, phoneNumber: +79644054946, providerId: firebase}], providerId: firebase, creationTimestamp: 1557420327980, lastSignInTimestamp: 1558848790729, isEmailVerified: false}
void _signInWithPhoneNumber() async {
final AuthCredential credential = PhoneAuthProvider.getCredential(
verificationId: _verificationId,
smsCode: _smsController.text,
);
final FirebaseUser user = await _auth.signInWithCredential(credential);
final FirebaseUser currentUser = await _auth.currentUser();
assert(user.uid == currentUser.uid);
debugPrint('user: $user');
setState(() {
if (user != null) {
Navigator.pushNamed(context, '/amenities');
} else {
_message = 'Вход не выполнен';
}
});
}
I need to extract PhoneNumber from "user" to send to server in Json
I'm pretty sure you can grab the phone number with just user.phoneNumber

Resources