Flutter firebase email/password error handling doesn't check blank fields properly
It looks like when the user did not even tap the username or password text fields, the email
and password
strings are null. But if the user types something (therefore changing the email
and password
strings) and then erases what he typed, the strings won't be null
, they will be equal to the empty string ""
, which is different from null
. Therefore, your control flow will jump straight to the last else
you have there, which is not what you want.
Consider adding checks for when email.isEmpty
or when password.isEmpty
to capture these events, or initializing your email
and password
strings to ""
in the first place. This way you make sure they won't be null
, and you just have to replace email == null
by email.isEmpty
and password == null
by password.isEmpty
in your code and everything should work fine.
vpxoxo
Updated on December 18, 2022Comments
-
vpxoxo over 1 year
Hello Flutter newbie here! I have setup the login and error checking part.
I want to do some checking on the fields, but I realize if the user does the following behavior, my code for error checking won't work:
- enter some text in email textfield
- enter some text in password textfield
- backspace delete the text in email textfield
- hit the flat button to submit
the code will pass the if checking and go ahead to sign in... but I thought since the email textfield is empty by the time I hit the button, it should still follow the if checking?
thanks in advance!
FlatButton( onPressed: () async { if (password == null && email == null) { print('empty sign in info'); setState(() { alertText = 'You have not entered your login info!'; }); } else if (password == null) { setState(() { alertText = 'Password cannot be blank!'; }); } else if (email == null) { setState(() { alertText = 'Email cannot be blank!'; }); } else { setState(() { showSpinner = true; }); try { final newUser = await _auth.signInWithEmailAndPassword( email: email, password: password); if (newUser != null) { Navigator.pushNamed(context, ViewScreen.id); } } catch (e) { print(e); } } },