The property 'uid' can't be unconditionally accessed because the receiver can be 'null' - flutter

User is not working. I'm not uploading a collection in Firebase
try {
FirebaseAuth.instance.createUserWithEmailAndPassword
(email: kEmail.text, password: kPassword.text)
.then((value) {
userCollection.doc(value.user.uid).set({
'userName': kUserName,
'email': kEmail,
'password': kPassword,
'uid': value.user.uid
});
});
} catch (err) {
print(err.toString());
}

User can be null. So do null checking first like
try {
FirebaseAuth.instance
.createUserWithEmailAndPassword(
email: kEmail.text, password: kPassword.text)
.then((value) {
if(value!=null && value.user != null){
userCollection.doc(value.user.uid).set({
'userName': kUserName,
'email': kEmail,
'password': kPassword,
'uid': value.user.uid
});
}else{
throw Error();
}
});
} catch (err) {
print(err.toString);
}
or a simple sol will be
..
Rest of the code...
userCollection.doc(value.user!.uid)
....Rest of the code //Add ! after user

change it to like this
(e.data() as dynamic)['myFieldOne']
https://i.stack.imgur.com/IhA7h.png

Related

Create an user in Firebase without automatically login

I have wrote a code, which should avoid the automatically login when an user get created.
The code worked until I used the dart migration tool. Now when I use this code with null-safety, then the secondaryApp is not created and another user get logged in.
Can someone please explain me, what I am doing wrong? I need to fix this code as fast as possible, but I just can't find the mistake.
I really appreciate any help.
code login:
InkWell(
onTap: () async {
await authProvider.signUpUser(
usernameController.text.trim(),
emailController.text.trim(),
passwordController.text.trim(),
firstNameController.text.trim(),
lastNameController.text.trim(),
_birthDateInString,
_genderSelected);
})
code (database request):
Future<bool> signUpUser(String username, String email, String password,
String firstName, String lastName, String? birthday, String? gender) async {
try {
_status = Status.Authenticating;
notifyListeners(); //changing status
FirebaseApp secondaryApp = await Firebase.initializeApp(
name: 'Secondary',
options: Firebase.app().options,
);
try {
UserCredential? credential = await FirebaseAuth.instanceFor(
app: secondaryApp)
.createUserWithEmailAndPassword(email: email, password: password)
.then((result) async {
//User user = result.user;
_userServices.createUser(
uid: result.user!.uid,
username: username,
email: email,
firstName: firstName,
lastName: lastName,
birthday: birthday,
gender: gender,
status: 'aktiv',
role: 'User',
);
});
print('user created');
await credential?.user!.sendEmailVerification();
} on FirebaseAuthException catch (e) {
print(e);
}
print('secondapp deleted');
await secondaryApp.delete();
_status = Status.Unauthenticated;
notifyListeners();
print('secondapp deleted');
return true;
} catch (e) {
_status = Status.Unauthenticated;
notifyListeners();
print(e.toString());
return false;
}
}
A little difficult to completely debug your project without a little more context but I tried to clean up just a bit and add a few print statements to help you out, hope this helps :)
Future<bool> signUpUser(
String username,
String email,
String password,
String firstName,
String lastName,
String? birthday,
String? gender,
) async {
try {
_status = Status.Authenticating;
notifyListeners(); //changing status
FirebaseApp secondaryApp = await Firebase.initializeApp(
name: 'Secondary',
options: Firebase.app().options,
);
/// here is our user:)
var _user;
try {
UserCredential? credential = await FirebaseAuth.instanceFor(app: secondaryApp)
.createUserWithEmailAndPassword(email: email, password: password);
print('we got our credentials lets take a look to see if we have them ${credential}');
var uid = credential.user?.uid;
if (uid != null) {
_userServices.createUser(
uid: uid,
username: username,
email: email,
firstName: firstName,
lastName: lastName,
birthday: birthday,
gender: gender,
status: 'aktiv',
role: 'User',
);
print('user created');
}
_user = credential?.user;
if (_user != null) {
await credential?.user.sendEmailVerification();
print('done with our send email verification!');
}
} on FirebaseAuthException catch (e) {
print(e);
}
if (_user != null) {
/// this means that we successfully authenticated our user consider returning from the function right here!!
}
print('secondapp deleted');
await secondaryApp.delete();
_status = Status.Unauthenticated;
notifyListeners();
print('secondapp deleted');
return true;
} catch (e) {
_status = Status.Unauthenticated;
notifyListeners();
print(e.toString());
return false;
}
}
One other thing that I noticed with your code is that if a User successfully authenticates then you automatically delete your secondaryApp. Is this your desired behavior?
I went ahead and added a note for you to add some code in there if you want but didn't want to dramatically change your code.

How can i store the url of the image instead of path of the image in firestore flutter

I want to store the URL of the image like this -
this is how i want to store url of the image in firestore
This is my current condition -
Currently it's showing the path of the image not the url
onPressed: () async {
if (imageFile == null) {
print("error");
} else {
try {
final ref = storage
.ref()
.child('user_profile_images')
.child(name + '.jpg');
ref.putFile(imageFile!);
url = await ref.getDownloadURL();
if (url != null) {
print(url);
}
} catch (e) {
print(e);
}
dynamic user = await auth.createUserWithEmailAndPassword(
email: email, password: password);
await FirebaseFirestore.instance
.collection('users')
.doc(name)
.set({
'email': email,
'name': name,
'profileurl': imageFile?.path,
'userid': auth.currentUser?.uid
}).then((value) {
try {
if (user != null) {
Navigator.pushNamed(context, '/dashboard');
}
} catch (e) {
print(e);
}
});
}
}),
I have a feeling the multiple try/catch blocks are getting in your way. In addition, it is never a good idea to mix then and await in a single block of code.
Combining those, try the following:
try {
final ref = storage
.ref()
.child('user_profile_images')
.child(name + '.jpg');
ref.putFile(imageFile!);
url = await ref.getDownloadURL();
if (url != null) {
print(url);
}
dynamic user = await auth.createUserWithEmailAndPassword(
email: email, password: password);
dynamic value = await FirebaseFirestore.instance
.collection('users')
.doc(name)
.set({
'email': email,
'name': name,
'profileurl': url // 👈
'userid': auth.currentUser?.uid
});
if (user != null) {
Navigator.pushNamed(context, '/dashboard');
}
} catch (e) {
print(e);
}
'profileurl': imageFile?.path, => 'profileurl': url?.toString(),

Apple Sign in Flutter Firestore overwrites displayname

I managed to get apple sign in working and create a userdoc on my firestore collection ('Users). However when I log out and sign in again with apple it overwrites the name "" ... Because it only logs the name the first time you log in with apple. How do I stop the name field to be overwritten everytime the same person signs out and in again?
case AuthorizationStatus.authorized:
try {
final res = await FirebaseAuth.instance.signInWithCredential(credential);
if (fixDisplayNameFromApple != null && res.user!.displayName == null) {
await res.user!.updateDisplayName(fixDisplayNameFromApple);
res.user!.reload();
}
FirebaseFirestore.instance.collection('Users').doc(res.user!.uid).set({
'name' : fixDisplayNameFromApple,
'email': res.user!.email,
'uid': res.user!.uid,
'image': 'https://merakiapp.be/wp-content/uploads/2022/06/appleUser.png',
}, SetOptions(merge: true));
return res.user;
} catch (e) {
print("error");
}
break;
I tried to check if the doc already exists so it doesn't create (overwrites) the original doc. But then it doesn't create a doc on firestore:
case AuthorizationStatus.authorized:
try {
final res = await FirebaseAuth.instance.signInWithCredential(credential);
if (fixDisplayNameFromApple != null && res.user!.displayName == null) {
await res.user!.updateDisplayName(fixDisplayNameFromApple);
res.user!.reload();
}
await FirebaseFirestore.instance
.collection("Users")
.doc(res.user!.uid)
.get()
.then((doc) {
if(doc.exists) {
return res.user;
} else {
FirebaseFirestore.instance.collection('Users').doc(res.user!.uid).set({
'name' : fixDisplayNameFromApple,
'email': res.user!.email,
'uid': res.user!.uid,
'image': 'https://merakiapp.be/wp-content/uploads/2022/06/appleUser.png',
}, SetOptions(merge: true));
return res.user;
}
});
} catch (e) {
print("error");
}
break;

error : display a red line under this statement _userFromFirebaseUser(userCredential.user);

hi every one I'm trying making my app with flutter . it is contains a sign up page so I write the code and I'm retrieving an information from the firebase after I upload it .
the below code is the sign up code
UserModel? _userFromFirebaseUser(User userCredential) {
return userCredential != null
? UserModel(
id: userCredential.uid,
bannerImageUrl: '',
name: '',
email: '',
profileImageUrl: '')
: null;
}
Stream<UserModel?> get userCredential {
return auth
.authStateChanges()
.map((userCredential) => _userFromFirebaseUser(userCredential!));
}
Future SignUp(email, password) async {
var formdata = formstate.currentState;
if (formdata!.validate()) {
print("valid");
formdata.save();
try {
UserCredential userCredential =
(await auth.createUserWithEmailAndPassword(
email: myemail!, password: mypassword!));
FirebaseFirestore.instance
.collection('Users')
.doc(userCredential.user!.uid)
.set({'name': email, 'email': email});
_userFromFirebaseUser(userCredential.user);
return userCredential;
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
Navigator.of(context).pop();
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
Navigator.of(context).pop();
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
} else {}
}
and the red line appears on this line _userFromFirebaseUser(userCredential.user); as it is appears in the picture . please help me
userCredential.user is User? not User
change the method parameter
UserModel? _userFromFirebaseUser(User? userCredential) {
return ....
}

Error handling pseudo already exists flutter firebase

I have a small question about try/catch with dart.
How can i add my script for check if a pseudo already exist in my function SignUp ?
_signUp(String _email, String _password, String _pseudo) async {
try {
//Create Get Firebase Auth User
if (_formKey.currentState.validate()) {
await auth.createUserWithEmailAndPassword(
email: _email, password: _password);
//problem here
users.get().then((querySnapshot) {
querySnapshot.docs.forEach((result) {
var pseudoDoc = result.data()['pseudo'];
if (pseudoDoc != _pseudo) {
users.doc(auth.currentUser.uid).set({
'pseudo': _pseudo,
'email': _email,
});
} else {
throw 'Pseudo already exist';
}
});
});
//
}
} on FirebaseAuthException catch (error) {
CoolAlert.show(
context: context,
type: CoolAlertType.error,
text: error.message,
);
}
}
}```