Using Firebase in Flutter: Part 2 – User Registration and Login

In Part 1 (or if you want to skip, here is the link to part 3) we set up Firebase in our Flutter project. In this part we will use it to register and login a user. The first thing we have to do is enable email authentication in Firebase

Once we have done that we are ready to initialize Firebase in our app. We are going to have to modify our main function in main.dart like so:

import 'package:firebase_core/firebase_core.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

Registration

To register a user with firebase we first need to import firebase auth import 'package:firebase_auth/firebase_auth.dart'; and get an instance of the auth class in our state final _auth = FirebaseAuth.instance;

Next we can just register a user with the following:
try {
    final newUser = await _auth.createUserWithEmailAndPassword(
        email: email, 
        password: password);
    
     if (newUser != null){
        Navigator.pushNamed(context, NextScreen.id);
     }
} catch (e) {
     print(e);
}

Now if you go back to Firebase, under authentication, you should be able to see the user you just registered.

Login

Next up is login. The code is as straight forward and the registration portion and only requires you do the following:

try {
     final user = await _auth.signInWithEmailAndPassword(
        email: email, 
        password: password);
                      
     if (user != null) {
        Navigator.pushNamed(context, NextScreen.id);
     }

} catch (e) {
     print(e);  
}

Also, to log out you just need to call the following:

 _auth.signOut();

That’s it! Enjoy!