Flutter firebase authentication error crashing my app - flutter

signInsignUpButtons(context, true, () {
try {
FirebaseAuth.instance
.signInWithEmailAndPassword(
email: _emailTextController.text,
password: _passwordTextController.text)
.then((value) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => homescreenPage(),
));
});
} on FirebaseAuthException catch (error) {
print(error.message);
Fluttertoast.showToast(
msg: error.message.toString(), gravity: ToastGravity.TOP);
}
// using firebase api checks whether email and password is correct registered
}),
I'm trying to show authentication errors from firebase such as incorrect password/email (when the user presses the sign in button). Instead of printing the error and displaying a pop up message on the app, it just freezes.
Ive tried using this line which is without fluttertoast
FirebaseAuth.instance
.signInWithEmailAndPassword(
email: _emailTextController.text,
password: _passwordTextController.text)
.then((value) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => homescreenPage(),
)).onError((error, stackTrace) {
print("Error ${error.tostring()}");
})
})
But then again, it just doesn't print the error and my app freezes.
Im using these dependancies:
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
firebase_core: ^2.4.1
firebase_auth: ^4.2.5
fluttertoast: ^8.1.2

Since signInWithEmailAndPassword is a future, you should use an async function and await in the try-catch block. Something like this should work:
void _signIn() async {
try {
await FirebaseAuth.instance.signInWithEmailAndPassword(
email: <email>,
password: <password>,
);
} on FirebaseAuthException catch (e) {
// catch FirebaseAuthException errors here
} catch (e) {
// catch other exceptions, for example no network
}
}

Related

MissingPluginException(No implementation found for method DocumentReference#set on channel plugins.flutter.io/firebase_firestore)

I want to set data to firebase firestore and this error occured.
Future _signUp(UserModel user) async {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: MySnackBar(msg: 'Please wait...')));
late final UserModel f_user;
try{
f_user = UserModel(MyEncrypter().encrypt(user.firstName), MyEncrypter().encrypt(user.lastName),
MyEncrypter().encrypt(user.email), MyEncrypter().encrypt(user.username), MyEncrypter().encrypt(user.password));
// await FirebaseAuth.instance.createUserWithEmailAndPassword(email: user.email, password: user.password);
await FirebaseFirestore.instance.collection('Users').doc(f_user.username).set(f_user.toJson());
Navigator.pushReplacement(context, MaterialPageRoute(builder: ((context) => HomeScreen())));
}catch(e){
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: MySnackBar(msg: 'Something went wrong! Please try again : ${e}')));
print(e);
}
}

Cant register FireBase user from Flutter

I am unable to register an user from my app written in Flutter. I am also unable to get some form for error message. I can debug and see my createUser function is called and the arguments looks good. Nothing happens after I call "FirebaseAuth.instance.createUserWithEmailAndPassword". No exception and nothing is printed in the FireBase emulator console. What am I missing here? Here is what I got:
Emulator:
Running on 127.0.0.1:9099
main.dart:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform,);
try {
await FirebaseAuth.instance.useAuthEmulator('localhost', 9099);
} catch (e) {
// ignore: avoid_print
print(e);
}
runApp(
MaterialApp(
title: "Foo",
home: buildContent(),
),
);
}
Registration function:
void createUser() async {
print("createUser()");
try {
final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: nameController.text,
password: passwordController.text,
);
//final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: nameController.text, password: passwordController.text);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
}
Edit:
I keep getting this message when i call "createUserWithEmailAndPassword"
W/System (26859): Ignoring header X-Firebase-Locale because its value was null.
In your createUser() Function i think you're sending empty values to firebase
request parameters like this and try it again
void createUser(String name, String Password) async {
print("createUser()");
try {
final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: name,
password: password,
);
print("User Created Success);
//final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: nameController.text, password: passwordController.text);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
}
So after some trail and error I ended up adding:
android:usesCleartextTraffic="true"
To the manifest file:
...\my_project\android\app\src\main\AndroidManifest.xml
I am not sure I like the "fix" as I think the requests are sent unencrypted. A google search gives me this description:
Android 6.0 introduced the useCleartextTraffic attribute under application element in android manifest. The default value in Android P is “false”. Setting this to true indicates that the app intends to use clear network traffic

'PresentPaymentSheetParameters' is deprecated and shouldn't be used. Parameters are now inherited from initPaymentSheet

I am integrating Stripe Payment Gateway into my e-commerce application. I am new to stripe payment gateway, I am facing a depreciation error which is as
'parameters' is deprecated and shouldn't be used. Params are now inherited from initPaymentSheet so this 'parameters' can be removed.
The current stripe plugin I am using is flutter_stripe: ^3.3.0. Just want to know how to fix this depreciation issue. Attaching the error screenshot also
CODE IS AS :
displayPaymentSheet(OrderProvider orderProvider) async {
try {
await Stripe.instance
.presentPaymentSheet(
parameters: PresentPaymentSheetParameters(
clientSecret: paymentIntentData!['client_secret'],
confirmPayment: true,
))
.then((newValue) {
print('payment intent ${paymentIntentData!['id']}');
print('payment intent ${paymentIntentData!['client_secret']}');
print('payment intent ${paymentIntentData!['amount']}');
print('payment intent $paymentIntentData');
//orderPlaceApi(paymentIntentData!['id'].toString());
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: const Text("Paid successfully")));
orderProvider.success = true;
Navigator.pop(context);
setState(() {
paymentIntentData = null;
});
}).onError((error, stackTrace) {
print('Exception/DISPLAYPAYMENTSHEET==> $error $stackTrace');
});
} on StripeException catch (e) {
print('Exception/DISPLAYPAYMENTSHEET==> $e');
showDialog(
context: context,
builder: (_) => AlertDialog(
content: Text("Cancelled "),
));
} catch (e) {
print('$e');
}
}
Try using initPaymentSheet.
await Stripe.instance
.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: "",
),
)

Flutter how to stop auto login using firebase SMS

When users first open the app, I want them to authenticate themselves by phone number. When they get the sms code and hit login button, the phone number and other information are sent to the server together.
However, when I press the code verification button, it automatically logs the user in without login button pressing so I cannot send data accordingly.
FirebaseAuth.instance.authStateChanges().listen((user) {
if (user == null) {
print("signed out - MyAppState");
} else {
print("signed in - MyAppState");
Navigator.push(context,
MaterialPageRoute(builder: (context) => BottomBarScreen()));
}
});
try {
_testPhoneValidation(_phoneNumberController.text);
await _auth.verifyPhoneNumber(
phoneNumber: "+82" + _phoneNumberController.text.substring(1),
timeout: const Duration(seconds: 5),
verificationCompleted: verificationCompleted,
verificationFailed: verificationFailed,
codeSent: codeSent,
codeAutoRetrievalTimeout: (verificationId) {},
);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('failure: ${e.toString().substring(11)}'),
));
}
this is my current code related to login with Firebase.
I searched how to stop auto login but didn't quite find the right answer.
So I just changed the login logic to : send info when Firebase auth state changes.
There isn't much change in the code and I think it was a dumb mistake that I made not to think about changing the logic.
FirebaseAuth.instance.authStateChanges().listen((user) {
if (user == null) {
print("signed out");
} else {
print("signed in");
signIn();
}
});
Future<void> signIn() async {
await postAppToken(
await _getToken(),
_packageInfo.appName,
_packageInfo.version,
Theme.of(context).platform.toString().substring(15),
await _getPhoneNum())
.then((value) {
print("signIn");
Navigator.push(context,
MaterialPageRoute(builder: (context) => BottomBarScreen()));
}
);
}
So I just added a Future to post related information to the server when user is automatically logged in. This solved my problem.
You should do nothing on " verificationCompleted" callback.
just write like this
verificationCompleted: (PhoneAuthCredential credential) {},
Because verificationCompleted is for automatic handling of the SMS code on Android devices.

Handle Firebase_Auth errors and show errors on screen

I want to handle firebase_auth exceptions and show the error messages on the screen. I have a couple of questions regarding displaying the error messages on the screen.
Is there something that displays the messages automatically?
or do I need to provide a textfield or label for displaying the message?
I am using the latest package: firebase_auth: ^3.0.1
Here is my code for logging in:
RoundedButton(
title: 'Log In',
colour: Colors.lightBlueAccent,
onPressed: () async {
setState(() {
showSpinner = true;
});
try {
UserCredential userCredential = await _auth.signInWithEmailAndPassword(email: email, password: password);
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
print('No user found for that email.');
} else if (e.code == 'wrong-password') {
print('Wrong password provided for that user.');
}
}
},
),
Everything here works but I want to display the error messages rather than put them in the console. How do I do this?