Add Firebase Authentication

Check if Authentication is enabled on firebase

Firebase console with Auth enabled

Add package firebase_auth to pubspec.yaml

firebase_auth: ^4.17.5

Modify main.dart , we are checking if the current user is null

 home: (FirebaseAuth.instance.currentUser == null)
                ? const LoginScreen()
                : const HomeScreen(),

Login and registration of the user is done with login_screen.dart

create a member variable _LoginScreenState

 final _auth = FirebaseAuth.instance;

search for GestureDetector of the login button

GestureDetector(
              onTap: () async {
                try {
                  await _auth.signInWithEmailAndPassword(
                      email: email!, password: password!);
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => const HomeScreen(),
                      fullscreenDialog: false,
                    ),
                  );
                } on FirebaseAuthException catch (err) {
                  if (err.code == "user-not-found") {
                    try {
                      await _auth
                          .createUserWithEmailAndPassword(
                              email: email!, password: password!)
                          .then((user) {
                        user.user!.sendEmailVerification();
                        createNewUserData();
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const HomeScreen(),
                            fullscreenDialog: false,
                          ),
                        );
                      });
                    } catch (err) {}
                  } else {
                    showDialog(
                      context: context,
                      builder: (context) {
                        return AlertDialog(
                          title: const Text("Error"),
                          content: Text(err.message!),
                          actions: [
                            TextButton(
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                              child: const Text("Ok!"),
                            ),
                          ],
                        );
                      },
                    );
                  }
                }
              },
              child: Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(14.0),
                  gradient: const LinearGradient(
                    colors: [
                      Color(0xFF73A0F4),
                      Color(0xFF4A47F5),
                    ],
                  ),
                ),
                height: 47.0,
                width: MediaQuery.of(context).size.width * 0.3,
                child: Text(
                  "Login",
                  style: kCalloutLabelStyle.copyWith(color: Colors.white),
                ),
              ),
            ),

Test, login and registration => testuser@flutterdevcamp.com -> it will navigate to Home screen

! If you get an error.

[!] Automatically assigning platform `iOS` with version `9.0` on target `Runner` because no platform was specified. Please specify a platform for this target in your Podfile. See [https://guides.cocoapods.org/syntax/podfile.html#platform] Error running pod install

run

cd ios
pod deintegrate
pod repo update
pod install

If stuck switch to this branch.

To Wrap it up lets add a forgot password functionality

GestureDetector(
          onTap: () {
            _auth.sendPasswordResetEmail(email: email!).then(
                  (value) => {
                    showDialog(
                        context: context,
                        builder: (context) {
                          return AlertDialog(
                            title: Text("Email Sent!"),
                            content:
                                Text("The password reset email has been sent!"),
                            actions: [
                              TextButton(
                                onPressed: () {
                                  Navigator.of(context).pop();
                                },
                                child: Text("OK!"),
                              ),
                            ],
                          );
                        })
                  },
                );
          },
          child: Container(
            child: Text(
              "Forgot Password?",
              style: kCalloutLabelStyle.copyWith(
                color: Color(0x721B1E9C),
              ),
            ),
          ),
        ),

Logout

sidebar_screen.dart -> Look for Log out , add a GestureDetector

final FirebaseAuth auth = FirebaseAuth.instance;
GestureDetector(
                onTap: () {
                  Future.wait([
                    auth.signOut(),
                  ]);
                  showDialog(
                    context: context,
                    builder: (context) {
                      return AlertDialog(
                        title: const Text("Message"),
                        content: const Text("Logged out successfully!"),
                        actions: [
                          TextButton(
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                            child: const Text("Ok!"),
                          ),
                        ],
                      );
                    },
                  );
                },
                child: Text(
                  "Log out",
                  style: kSecondaryCalloutLabelStyle,
                ),
              ),

Last updated