Is setState() ignored by try & catch?

Issue

I use Firebase Auth to allow users to sign up.
If the user registers the correct email address and a sufficiently secure password, they will be registered with Firebase Auth.

I can register, but when I fail to sign up, I don’t get an error.

String _state = ""; //global

Future signUp(String email, String password) async {
 try {
   UserCredential userCredential = await FirebaseAuth.instance
       .createUserWithEmailAndPassword(email: email, password: password);
 } on FirebaseAuthException catch (e) {
   if (e.code == 'weak-password') {
     setState(() {
       _state = ('The password provided is too weak.');
     });
   } else if (e.code == 'email-already-in-use') {
     setState(() {
       _state = ('The account already exists for that email.');
     });
   }
 } catch (e) {
   setState(() {
     _state = e.toString();
   });
 }
}

Referred here.
This code executes createUserWithEmailAndPassword() by passing the email address and password as arguments.
I’m trying to display on the screen the cause of a sign-in failure with try & catch statement.

But for some reason setState() doesn’t change the Text() that has global _state.

    @immutable
class signUp extends StatefulWidget {
  static String route = '/signup';
  const  signUp({Key? key}) : super(key: key);

  @override
  _signUp createState() => _signUp();
}

class _signUp extends State<signUp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: myAppBar(context), //custom appBar. ignore this.
        body: const Center(
          child: Text( 
             _state
          ),
        ));
  }
}

I declared Text() in StatefulWidget so that it can be updated with setState().

But for some reason setState() is ignored and Text(_state) is not executed.
I feel that the cause of this problem is in the try & catch statement, but I don’t know what to do.

What should I do to display the sign-up results as text?

Thank you.

Solution

I changed code like this; this solved my issue.

String stateCode = "";
    try {
      UserCredential userCredential = await FirebaseAuth.instance
          .createUserWithEmailAndPassword(email: email, password: password);
    } on FirebaseAuthException catch (e) {
      if (e.code == 'weak-password') {
        stateCode = ('The password provided is too weak.');
      } else if (e.code == 'email-already-in-use') {
        stateCode = ('The account already exists for that email.');
      } else {
        stateCode = "error: " + e.code;
      }
    } catch (e) {
      stateCode = "error: " + e.toString();
    }

    setState(() {
      _state = (stateCode);
    });

All I had to do was display the e.code when an exception occurred.

Answered By – Beginner_

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *