I am trying to refactor my code by creating a class that registers a user using the Google email method so it is more manageable.
I have a couple of problems:
I want to use a try/catch
so I can catch any errors.
I need to use await
but I am getting this error:
The await expression can only be used in an async function. Try marking the function body with either 'async' or 'async'.*
Below is the code I am trying to breakout and create a new class with:
class RegisterUser {
final _auth = FirebaseAuth.instance;
bool registrationFail = false;
String errorMessage = "";
try {
final newUser = await _auth.createUserWithEmailAndPassword(
email: widget.email, password: widget.password);
if (newUser != null) {
ref
.read(usersNotifierProvider.notifier)
.updateuserID(newUser.user!.uid);
ref
.read(usersNotifierProvider.notifier)
.updateEmail(newUser.user!.email!);
/// Send the email verification
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => const VerifyEmailScreen()));
} else {
setState(() {
registrationFail = true;
});
}
setState(() {
showSpinner = false;
});
} on FirebaseAuthException catch (error) {
switch (error.code) {
case "ERROR_INVALID_EMAIL":
case "invalid-email":
errorMessage =
"Your email address appears to be malformed.";
break;
case "email-already-in-use":
errorMessage = "Email is already in use.";
break;
case "ERROR_WRONG_PASSWORD":
case "wrong-password":
errorMessage = "Your password is wrong.";
break;
case "weak-password":
errorMessage = "Weak password";
break;
case "ERROR_USER_NOT_FOUND":
case "user-not-found":
errorMessage = "User with this email doesn't exist.";
break;
case "ERROR_USER_DISABLED":
case "user-disabled":
errorMessage =
"User with this email has been disabled.";
break;
case "ERROR_TOO_MANY_REQUESTS":
case "too-many-requests":
errorMessage = "Too many requests. Try again later.";
break;
case "ERROR_OPERATION_NOT_ALLOWED":
case "operation-not-allowed":
errorMessage =
"Signing in with Email and Password is not enabled.";
break;
default:
errorMessage =
"An undefined Error happened. Please try again.";
}
if (errorMessage != "") {
ScaffoldMessenger.of(context).showSnackBar((SnackBar(
content: Center(
child: Text(
errorMessage,
style: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.w900),
),
),
behavior: SnackBarBehavior.floating,
margin: EdgeInsets.only(
bottom: MediaQuery.of(context).size.height - 100,
left: 10,
right: 10,
),
backgroundColor: Colors.redAccent,
)
)
);
}
}
}
How do I create a class for this? Thanks
You have your try/catch in the body of your class not in a function. Not how classes are created.
class RegisterUser {
RegisterUser() {
_loadUser();
}
_loadUser() async {
// Do your try catch
}
}