Firebase_auth - Null check operator used on a null value - firebase

I've gone through all the similar questions but none is similar to my issue.
I have the function below for verifying the OTP sent the mobile number whiles using the verifyPhoneNumber() on the FirebaseAuth instance.
Future<User?> manualVerification(code) async {
try {
await _firebaseAuth .signInWithCredential(
PhoneAuthProvider.credential( verificationId: _verificationCode, smsCode: code, ))
.then((value) async {
if (value.user != null) {
print("User not null");
print("user ${value.user}");
return value.user;
} else {
print("User null!");
}
}).catchError((err) {
print("manual verification Failed: $err"); return err; });
} catch (e) {
print("manualVerification Catch| $e");
}
}
However, Once the function is called and completes, I get "User not Null" in the console as expected.
But I also get "Null check operator used on a null value" and "type '_CastError' is not a subtype of type 'FutureOr<User?>'".
Also the function return null for Value.user. But the user is created on the Firebase Console.
I have so far modified the function to this:
Future<User?> manualVerification(code) async {
try {
PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.credential(
verificationId: _verificationCode,
smsCode: code,
);
final authCredential =
await _firebaseAuth.signInWithCredential(phoneAuthCredential);
if (authCredential.user != null) {
print("Got User");
print("${authCredential.user!.uid}");
return authCredential.user;
}
} on FirebaseException catch (e) {
print("manualVerification Catch| ${e.message}");
}
}
And though the function prints the uid of the user I get this error:
[VERBOSE-2:ui_dart_state.cc(186)] Unhandled Exception: Null check operator used on a null value
#0 UserInfo.uid (package:firebase_auth_platform_interface/src/user_info.dart:52:24)
#1 UserInfo.toString (package:firebase_auth_platform_interface/src/user_info.dart:57:144)
#2 StringBuffer.write (dart:core-patch/string_buffer_patch.dart:64:22)
#3 StringBuffer.writeAll (dart:core-patch/string_buffer_patch.dart:102:7)
#4 IterableBase.iterableToFullString (dart:collection/iterable.dart:267:14)
#5 ListBase.listToString (dart:collection/list.dart:43:20)
#6 List.toString (dart:core-patch/growable_array.dart:489:33)
#7 _StringBase._interpolate (dart:core-patch/string_patch.dart:855:19)
#8 User.toString (package:firebase_auth/src/user.dart:357:5)
#9 _StringBase._interpolate (dart:core-patch/string_patch.dart:855:19)
#10 AuthViewModel.verifyPin (package:sxxxxx/ui/auth/auth_viewmodel.dart:81:29)
I have tried the same code with firebase_auth: ^1.0.3 and ^1.1.0
I'm on Flutter 2.0.4 • channel stable.
Please help

update your firebase auth version.
This solved my issue

Related

The getter 'user' was called on null on a Firebase Realtime Database + Flutter App

Today i updated the android emulator i use frecuently and for some reason im getting this error. I already update all possible dependences and packages.
I/FirebaseAuth(11346): [FirebaseAuth:] Preparing to create service connection to fallback implementation
W/System (11346): Ignoring header X-Firebase-Locale because its value was null.
E/flutter (11346): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: NoSuchMethodError: The getter 'user' was called on null.
E/flutter (11346): Receiver: null
E/flutter (11346): Tried calling: user
E/flutter (11346): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter (11346): #1 _RegistrarseState.signupNewUser (package:mundoplay/code/registrarse/registrarse.dart:511:9)
E/flutter (11346): <asynchronous suspension>
This is part of my current code for the user to register:
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
void signupNewUser(BuildContext context) async {
showDialog(context: context,
barrierDismissible: false,
builder: (BuildContext context)
{
return barraProgreso(mensaje: "Creando su cuenta, espere...",);
});
final firebaseUser = (await _firebaseAuth
.createUserWithEmailAndPassword(
email: email.text, password: password.text)
.catchError((errMsg) {
Navigator.pop(context);
setState(() {
_error = Errors.show(errMsg.code);
});
})).user;
if (firebaseUser != null)
{
Map userDataMap = {
"nombre": nombre.text.trim(),
"apellido": apellido.text.trim(),
"email": email.text.trim(),
"password": password.text.trim(),
"celular": celular.text.trim(),
"direccion": direccion.text.trim(),
"localidad": localidad.text.trim(),
};
usersRef.child(firebaseUser.uid).set(userDataMap).then((value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('email', email.text);
//Navigator.push(context, new MaterialPageRoute(builder: (context) => new SeleccionarConsola()));
});
My register and login works with a form with TextEditingControllers that are set to the controller value.
I'm working with the firebase realtime database... any extra info, just ask me and i will try add it. THANKS!
According to the docs, catchError
Returns a new Future that will be completed with either the result of this future or the result of calling the onError callback.
So when you initialize your firebaseUser, you use a catchError that doesn't return nothing (i.e. implicitely returns null). You can see this in practice with a simple example:
Future<T> handleError<T>(Future<T> future) {
return future.catchError((e) {
print("An error occurred.");
// Not returning anything here!
});
}
void main() async {
// When no error occurs, it will print 1
print(await handleError(Future.value(1)));
// When an error occurs, it will print null
print(await handleError(Future.error(Error())));
}
Since you've already said that you're not connected to the internet since you're using an emulator, an error is being thrown inside the future (maybe a "no internet exception" kind of error), the future is returning null and thus the "The getter 'user' was called on null." message.
There are two ways you can avoid this:
Using the ?. operator:
final firebaseUser = (await _firebaseAuth
.createUserWithEmailAndPassword(
email: email.text, password: password.text)
.catchError((errMsg) {
Navigator.pop(context);
setState(() {
_error = Errors.show(errMsg.code);
});
}))?.user; // <- use it here!
Doing it step-by-step:
final result = await _firebaseAuth.createUserWithEmailAndPassword(
email: email.text,
password: password.text,
).catchError((e) {
Navigator.pop(context);
setState(() => _error = Errors.show(errMsg.code));
});
// Early exit
if (result == null) return;
// Only retrieve the firebase user here
final firebaseUser = result.user;

Why My Update Email is not WORKING, Firebase and Flutter?

I want to build a function that update the user email in firebase so this is what I did:
1- checked if there is internet.
2- do user.updateEmail with the email I got from firestore after I uploaded it in the sign Up and It can't be null because I used it down and it also prints the error :
NoSuchMethodError: The method 'updateEmail' was called on null.
I/flutter ( 9769): Receiver: null
I/flutter ( 9769): Tried calling: updateEmail("omarkaram1st#gmail.com")
see It got the email but somehow it can't send an email;
Code :
switchAccount() async {
try {
final user = await _auth.currentUser();
final result = await InternetAddress.lookup('google.com');
try {
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
user.updateEmail(email);
AwesomeDialog(
btnOkText: 'Ok',
context: context,
headerAnimationLoop: false,
dialogType: DialogType.INFO,
animType: AnimType.BOTTOMSLIDE,
title: 'Info',
desc: 'A Reset Email Has Been Sent To $email',
btnOkOnPress: () {},
)..show();
}
} catch (e) {
print(e);
}
} on SocketException catch (_) {
AwesomeDialog(
btnOkText: 'Retry',
context: context,
headerAnimationLoop: false,
dialogType: DialogType.ERROR,
animType: AnimType.BOTTOMSLIDE,
title: 'Error',
desc:
'Make Sure That You Have an Internet Connection Before Pressing Retry',
btnOkOnPress: () =>
Navigator.pushReplacementNamed(context, '/HomePage'),
)..show();
}
}
It looks like user is null in your call to user.updateEmail(email). We can't say why that is from the code you shared, but the quick way to prevent the error is to check for null after calling await _auth.currentUser().
final user = await _auth.currentUser();
if (user != null) {
final result = await InternetAddress.lookup('google.com');
try {
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
user.updateEmail(email);
...
}
} catch (e) {
print(e);
}
}
else {
... do something relevant when no user is signed in
}

NoSuchMethodError: The method '[]' was called on null. -FIREBASE Flutter

I'm trying to delete a FirebaseUser, and It returns a null error. I dunno what's wrong with my code.
can somebody answer with a proper explanation cause I'm new to this error!
The error:
D/FirebaseAuth(16061): Notifying id token listeners about user ( r6Nn5Gxxxxxxxxxxxxxxx ).
I/flutter (16061): Deletion error NoSuchMethodError: The method '[]' was called on null.
I/flutter (16061): Receiver: null
I/flutter (16061): Tried calling: []("user")
Here's how I'm trying to delete the user:
new FlatButton(
child: Text("Delete"),
onPressed: () async {
if (password.text.length == 0) {
showInSnackBar("Please enter your password");
} else {
FirebaseUser firebaseUser =
await FirebaseAuth.instance.currentUser();
String uid = firebaseUser.uid;
var credential = EmailAuthProvider.getCredential(
email: firebaseUser.email,
password: password.text);
var result = await firebaseUser
.reauthenticateWithCredential(credential);
try {
await result.user.delete();
} on PlatformException catch (e) {
print("///////// ${e.code}");
String errorCde = e.code;
if (errorCde == "ERROR_WRONG_PASSWORD") {
showInSnackBar("Wrong password! Please try agian.");
} else if (errorCde == "ERROR_TOO_MANY_REQUESTS") {
showInSnackBar(
"You've tried too many times, Please try again in a while!");
} else if (errorCde ==
"ERROR_NETWORK_REQUEST_FAILED") {
showInSnackBar(
"Please check your internet connection");
}
} catch (e) {
print("Deletion error $e");
showInSnackBar("Something went wrong");
}
}
},
),

Flutter: PlatformException thrown by FireBase won't get caught

I have a function that is used to sign in to Firebase using firebase_auth, however, whenever an exception is thrown it isn't getting caught and still appears in the Android Studio console nor do the print statements in the catch block ever run.
How do I fix this?
signIn({String email, String password}) {
print('listened');
try {
FirebaseAuth.instance.signInWithEmailAndPassword(
email: email, password: password);
}
on PlatformException catch (signUpError) {
print(signUpError.code);
if (signUpError.code == 'ERROR_WEAK_PASSWORD') {
print('Weak Password');
}else if(signUpError.code=='ERROR_USER_NOT_FOUND'){
print('Invalid Username');
}
else{
print(signUpError.toString());
}
}
}
signInWithEmailAndPassword returns a Future<AuthResult> (it is asynchronous), therefore you need to use the catchError method to catch the error when calling an asynchronous method:
FirebaseAuth.instance.signInWithEmailAndPassword(email: email, password: password).then((result) {
print(result);
})
.catchError((error) {
print("Something went wrong: ${error.message}");
});
Check the following:
https://api.dart.dev/stable/2.3.0/dart-async/Future/catchError.html
https://medium.com/firebase-tips-tricks/how-to-use-firebase-authentication-in-flutter-50e8b81cb29f
The try catch blocks will work if the Firebase call is within an async function and the await statement is used when calling Firebase.
For example, in the following code an error getting the token will be trapped by the on PlatformException catch (... block but an error writing the token to FB RTDB won't be:
Future<void> _saveDeviceToken() async {
try {
final _currentUser = _firebaseAuth.currentUser;
final fcmToken = await _firebaseMessaging.getToken();
if (fcmToken != null) {
// Save the token to Firebase - NO AWAIT STATEMENT
globals.firebaseDatabase
.reference()
.child("pushTokens")
.child("${_currentUser.uid}")
.set({"token": fcmToken});
}
} on PlatformException catch (error, stackTrace) {
print("error: $error");
}
}
whereas adding the await statement, as in the following code, will trap errors in writing to FB RTDB as well:
Future<void> _saveDeviceToken() async {
try {
final _currentUser = _firebaseAuth.currentUser;
final fcmToken = await _firebaseMessaging.getToken();
if (fcmToken != null) {
// Save the token to Firebase - AWAIT STATEMENT ADDED
await globals.firebaseDatabase
.reference()
.child("pushTokens")
.child("${_currentUser.uid}")
.set({"token": fcmToken});
}
} on PlatformException catch (error, stackTrace) {
print("error: $error");
}
}
If you don't want to or can't use await then, as per Peter's answer, the solution is to use the catchError statement instead of try catch.

Flutter Error Firebase User ReauthenticateWithCredential

I am developing an app in flutter and I'll need to Re Authenticate user but I am getting below error
I/flutter (14968): Error: NoSuchMethodError: The method '[]' was called on null
I/flutter (14968): Receiver: null
I/flutter (14968): Tried calling: []("user")
Below is the code i am using to re authenticate user
FirebaseUser user = await FirebaseAuth.instance.currentUser();
print("User Email: ${user.email}");
AuthCredential authCredential = EmailAuthProvider.getCredential(
email: user.email,
password: _oldPassController.text,
);
print("Auth Credential: ${authCredential.toString()}");
user.reauthenticateWithCredential(authCredential).then((result) {
print("Success: $result");
}).catchError((error) {
print("Error: $error");
setState(() {
_isLoading = false;
});
if (error is PlatformException) {
PlatformException exception = error;
showAlertDialog(context, exception.message);
} else {
showAlertDialog(context, error.toString());
}
});
I don't have a fix for the actual problem (I think it's actually a Firebase-to-Flutter-project connection problem), but I have a workaround that works for me.
I simply use signInWithEmailAndPassword() in place of reauthenticateWithCredential(), and it seems to be working fine. Like so:
AuthResult authResult = await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
FirebaseUser firebaseUser = authResult.user;
After calling the signInWithEmailAndPassword(), the user is re-authenticated because they've recently been logged in.
Hope it's useful.

Resources