Home > Net >  Showing firebase auth error codes in flutter UI
Showing firebase auth error codes in flutter UI

Time:01-12

I'm new to flutter .So I was wondering if there is anyway that I can show the firebase auth error codes as the Errortext in textfield ? enter image description here

I am able to print the exception from firebase_auth but dont know how to give it as the errortext .

 try {
                  final newuser = await FirebaseAuth.instance
                      .createUserWithEmailAndPassword(
                    email: email ?? 'error',
                    password: password ?? 'error',
                  );

                  if (newuser != null) {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => ProfileDetail()),
                    );
                  }
                } catch (e) {
                  print(e);
                  
                }
              },

this is the textfield

   TextField(
                      onChanged: (value) {
                        username = value;
                      },
                      decoration: const InputDecoration(
                        border: UnderlineInputBorder(),
                        labelText: 'Username',
                        // errorText: 
                        
                      ),
                    ),

CodePudding user response:

You can use "showsnackBar"

try {
    showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) {
          return const Center(
            child:CircularProgressIndicator(),
          );
        });

    await FirebaseAuth.instance.signInWithEmailAndPassword(
      email: emailController.text.trim(),
      password: passwordController.text.trim(),
    );
    Navigator.of(context)
            .pushNamedAndRemoveUntil('/home', (route) => false);
  } on FirebaseAuthException catch (e) {
    if (e.code == 'user-not-found') {
       ScaffoldMessenger.of(context).showSnackBar(
       const SnackBar(content: Text('user-not-found')),
        );
      Navigator.of(context).pop();
    } else if (e.code == 'wrong-password') {
      ScaffoldMessenger.of(context).showSnackBar(
       const SnackBar(content: Text('wrong-password')),
        );
      Navigator.of(context).pop();
      
  }

CodePudding user response:

First declare a variable to hold errorText;

String? errorText;

Then extract the error like this,

try {
  // try block
} on FirebaseAuthException catch (e) {
  if (e.code == 'weak-password') {
    errorText = 'The provided password is too weak.';
  } else if (e.code == 'email-already-in-use') {
    errorText = 'The email is already in use.';
  }
  // set the value to your TextEditingController().
  controller.text = errortext ?? "";
} catch (e) {
  print(e);
}
  • Related