I am struggling to to show my custom error messages during login/sign up. The error messages that are showing up are the default ones coming from Firebase. I need to display the custom error messages in the code below depending on the error code. Please assist...
I'm not sure what's still missing. Iv'e tried everything but still not winning
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import '../widgets/auth/auth_form.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class AuthScreen extends StatefulWidget {
const AuthScreen({Key? key}) : super(key: key);
static const routeName = '/auth_screen';
@override
_AuthScreenState createState() => _AuthScreenState();
}
class _AuthScreenState extends State<AuthScreen> {
final _auth = FirebaseAuth.instance;
var _isLoading = false;
void _submitAuthForm(
String email,
String password,
String displayName,
String phoneNumber,
bool isLogin,
BuildContext ctx,
) async {
UserCredential authResult;
try {
setState(() {
_isLoading = true;
});
if (isLogin) {
authResult = await _auth.signInWithEmailAndPassword(
email: email,
password: password,
);
} else {
authResult = await _auth.createUserWithEmailAndPassword(
email: email, password: password);
await FirebaseFirestore.instance
.collection('userProfile')
.doc(authResult.user!.uid)
.set(
{
'displayName': displayName,
'email': email,
'phoneNumber': phoneNumber,
'uid': authResult.user!.uid,
},
);
}
} on FirebaseAuthException catch (error) {
var message = 'An error has occured.'; // default message
switch (error.code) {
case 'EMAIL_NOT_FOUND':
message = 'There is no user account with the email address provided.';
break;
case 'EMAIL_EXISTS':
message = 'The email address is already in use by another account.';
break;
case 'INVALID_PASSWORD':
message = 'Invalid password. Please enter correct password.';
break;
}
setState(() {
_isLoading = false;
});
showDialog(
context: context,
builder: (context) => CupertinoAlertDialog(
title: const Text('An error occured'),
content: Text(
error.message.toString(),
),
actions: [
TextButton(
child: const Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
),
);
}
}
CodePudding user response:
I think your problem lies in the fact that while you have defined a message variable, you are not using it inside the dialog. You are instead using error.message.toString()
.
showDialog(
context: context,
builder: (context) => CupertinoAlertDialog(
title: const Text('An error occured'),
content: Text(
error.message.toString(), /// <-------------- HERE
),
actions: [
TextButton(
child: const Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
),
);
Replace that with message and it should work.