How to set firebase uid to users document id? i'm getting error as "uid is null". Here is my code.
FirebaseAuth.instance.createUserWithEmailAndPassword(email:email, password: password).then((currentUser) => Firestore.instance
.collection("users")
.document(currentUser.uid)
.setData({ "uid": currentUser.uid,
}));
You can become the current user information with the .user ending and then you have access to the uid with currentUser.uid.
Future<void> createUser() async {
final FirebaseUser currentUser = (await FirebaseAuth.instance.createUserWithEmailAndPassword(email: 'Test#gmail.com', password: '123456')).user;
Firestore.instance.collection("users").document(currentUser.uid).setData({
"uid": currentUser.uid,
},
);
}
Related
I tried to save the docs from the collection "users" in Firebase with a phone number but to read these docs I need to call fonction these docs with number
model.User user = model.User(
uid: cred.user!.uid,
userName: userName,
portable: portable,
nni: nni,
email: email,
whatsapp: whatsapp,
photoUrl: photoUrl,
password: password,
);
await _firestore
.collection("users")
.doc(portable)
.set(user.toJson());
to read these data
Future<model.User> getUserDetails() async {
DocumentSnapshot snap =
await _firestore.collection('users').doc(portable).get();
return model.User.fromSnap(snap);
}
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;
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}');
In short, I want my Authenticated user by Email and Password in firebase firestore,
After successfully register my users only appears in a authentication pannel.
I am currently working with Flutter application where I use firebase_auth: ^1.1.1 package.
So I expect that after
UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: "abc#example.com",
password: "SuperSecretPassword!"
);
The function called from firebase_auth package which is createUserWithEmailAndPassword
I want this registed user in Firebase Database.
Firebase authentication is used to register a user while firestore is used for storing data. If you want to add the user to firestore also then you need to add the cloud_firestore plugin to your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
cloud_firestore: ^1.0.7
Then you can do:
final firestoreInstance = FirebaseFirestore.instance;
var firebaseUser = FirebaseAuth.instance.currentUser;
firestoreInstance.collection("users").doc(firebaseUser.uid).set(
{
"email" : "abc#example.com",
}).then((_){
print("success!");
});
This will create a collection called users with a document id equal to the authenticated user id, and inside of it you will have the email of the user.
.createUserWithEmailAndPassword creates a user in auth, if you check your auth tab you should see created user. It does not create user in firestore
for this you have to implement yourself .
below is a sample example
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
User user = (await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password))
.user;
//if create user succeeds
var user =UserModel(
userID:user.uid,
email:user.email)
FirebaseFirestore.instance
//save user based on their id from auth
.doc("users/${user.uid}")
.set(user.toJson());
Edit
you can create a user model
example:
class UserModel {
final String userID;
final String displayName;
final String email, pushToken;
final String phoneNumber;
final String profilePictureURL, dateJoined;
UserModel({
this.dateJoined,
this.userID,
this.email,
});
Map<String, Object> toJson() {
return {
'userID': userID,
'email': email == null ? '' : email,
'appIdentifier': 'my app',
'dateJoined': DateTime.now(),
};
}
}
....
check how to use json
In addition to the griffins answer, you could use a cloud function to respond to the user creation event (trigger onCreated). Then you can create the users collection, asynchronously, without overloading the flutter client. For example, an index.ts with the createUserInFirestore function:
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();
const db = admin.firestore();
export const createUserInFirestore = functions.auth.user().onCreate(
async (user) => {
return db.collection('users').doc(user.uid).set({
"email" : user.email,
"name" : user.displayName,
});
}
);
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?