skip to Main Content

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


  1. 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).

    Login or Signup to reply.
  2. createUserWithEmailAndPassword automatically logs the user in after creation. you don’t need to do signInWithEmailAndPassword, just navigate to home page immediately.

    onPressed: () async {
     try {
       final userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
         email: _emailController.text,
         password: _passwordController.text);
        
       assert(userCredential != null);
        
       String userId = userCredential.user!.uid;
    
       Navigator.pushReplacementNamed(context, '/home'));              
    } catch (e) {
       debugPrint(e.toString());
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search