I have a login screen with firebase authentication and error validation. When a user inserts their credentials, firebase does validation and returns error code. I am translating the error then displaying it on a snack bar. My issue is on clicking of the login button, I want the progress indicator to come up and if there are any errors caught, it must stop and only the snack bar must show. My code is as follows
myButtonOnPressed: () async {
try {
final newUser = await _auth.signInWithEmailAndPassword(
email: email,
password: password,
);
if (newUser != null) {
Navigator.pushNamed(context, HomeScreen.id);
}
} on FirebaseAuthException catch (e) {
///look for error conde in switch statement and return
///english error code
String fireBaseAuthErrorCode = funcFireBaseAuthErrors(e.code);
ScaffoldMessenger.of(context).showSnackBar(
///add SnackBar function
funcSnackBar(
errorMessage: fireBaseAuthErrorCode,
snackBarColor: Color(snackBarColor),
snackBarTextColor: Color(snackBarTextColor),
snackBarTextFont: snackBarTextFont,
snackBarTextSize: snackBarTextSize,
showErrorDuration: kLoginScreenSnackBarDisplayDuration,
),
);
}
},
How on earth do I do this?
I am assuming that you are using a
StatefulWidget
- using which this can be achieved with a boolean variable and conditional rendering in the button.Explanation
authInProgress
with initial value offalse
, indicating that process has not yet begun.setState
method set theauthInProgress
totrue
in thetry
block, and add afinally
block, set it back tofalse
. Thefinally
block will execute regardless of the outcome in thetry
block. So, in this case - whether login fails or succeeds, finally block is always executed.ElevatedButton
for this case, in which, ifauthInProgress
istrue
, we will renderCircularProgressIndicator()
, else theText()
, that you want to display.P.S.
login()
outside ofbuild()
for the sake of brevity.