Im building a sign up screen in flutter, and I wanted that right after creating a user, it would automatically login and redirect to home, this works but I think there may be a cleaner way to do it.
Im using firebase auth.
onPressed: () async {
final userCredential = FirebaseAuth.instance.createUserWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text).then(
(value) => FirebaseAuth.instance.signInWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text)).then(
(value) => Navigator.pushReplacementNamed(context, '/home'));
}
2
Answers
Creating a new user account in Firebase already signs them in, so there’s no need for that
signInWithEmailAndPassword
call.As Vivek commented, also consider listening for the
authStateChanges()
stream, so that you can show the correct screen based on the current auth state of your app – even when the user restarts it (at which point Firebase automatically restores their authentication state).createUserWithEmailAndPassword automatically logs the user in after creation. you don’t need to do signInWithEmailAndPassword, just navigate to home page immediately.