I want a dynamic error message instead of this static error message.
Please review my code and help me out with the code to show an error message in Flutter while logging in with Firebase.
I am making a login page for my app and I am using the Firebase authentication service for that. Now I am trying to show an error dialog message when a user attempts with the wrong credentials or any other case. And so for I have done this... I have coded this and it executes successfully but the error message is static "An unexpected error occurred", instead of this I want a dynamic error message which particularly shows what's wrong with the login credentials, for example, whether the email is badly formatted or password is wrong etc.
My code:
class LoginPage extends StatefulWidget {
final VoidCallback showRegisterPage;
const LoginPage({Key? key, required this.showRegisterPage}) : super(key: key);
@override
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final formKey = GlobalKey<FormState>(); //key for form
String name = "";
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
void showErrorMessage(Object error) {
String errorMessage;
if (error is String) {
errorMessage = error;
} else if (error is PlatformException) {
errorMessage = error.message ?? 'An unknown error occurred';
} else {
errorMessage = 'An unexpected error occurred';
}
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Error'),
content: Text(errorMessage),
actions: <Widget>[
ElevatedButton(
child: Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
Future LoginPage() async {
try {
await FirebaseAuth.instance.signInWithEmailAndPassword(
email: _emailController.text.trim(),
password: _passwordController.text.trim(),
);
} catch (error) {
showErrorMessage(error);
}
}
void showErrorMessage(Object error){
check this snippet for ref.