(Part 2) Firebase Email & Password Authentication in Flutter | Doctor Appointment App (2024)
Table of Contents
Introduction
In this tutorial, we will walk through the process of implementing email and password authentication in a Flutter application using Firebase. This guide is part of a series focused on developing a Doctor Appointment app, which utilizes Firebase for backend data storage and user authentication. By the end of this tutorial, you'll have a functional authentication system ready for your application.
Step 1: Set Up Firebase for Your Project
- Create a Firebase project by visiting the Firebase Console.
- Click on "Add project" and follow the prompts to configure your new project.
- Once your project is created, navigate to the project settings and add a new application for Android or iOS.
- Download the
google-services.json
(for Android) orGoogleService-Info.plist
(for iOS) and place it in the appropriate directory of your Flutter project. - Enable Email/Password Authentication:
- In the Firebase console, go to "Authentication" and then "Sign-in method."
- Toggle the switch to enable the Email/Password sign-in method.
Step 2: Install Required Packages
- Open your
pubspec.yaml
file and add the necessary Firebase packages:dependencies: firebase_core: ^latest_version firebase_auth: ^latest_version
- Run
flutter pub get
in your terminal to install the packages.
Step 3: Initialize Firebase in Your App
- In your
main.dart
file, initialize Firebase at the start of your app:import 'package:firebase_core/firebase_core.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); }
Step 4: Create Authentication Service
- Create a new Dart file named
auth_service.dart
for handling authentication logic. - Implement the following methods:
import 'package:firebase_auth/firebase_auth.dart'; class AuthService { final FirebaseAuth _auth = FirebaseAuth.instance; Future<User?> signInWithEmailAndPassword(String email, String password) async { try { UserCredential userCredential = await _auth.signInWithEmailAndPassword(email: email, password: password); return userCredential.user; } catch (e) { // Handle error (e.g. print or show message) return null; } } Future<void> signOut() async { await _auth.signOut(); } }
Step 5: Create Login UI
- Design a simple login form in your Flutter app. Here’s an example of how to set it up:
import 'package:flutter/material.dart'; import 'auth_service.dart'; class LoginPage extends StatelessWidget { final AuthService _authService = AuthService(); final TextEditingController emailController = TextEditingController(); final TextEditingController passwordController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Login")), body: Padding( padding: EdgeInsets.all(16.0), child: Column( children: [ TextField(controller: emailController, decoration: InputDecoration(labelText: "Email")), TextField(controller: passwordController, decoration: InputDecoration(labelText: "Password"), obscureText: true), ElevatedButton( onPressed: () async { User? user = await _authService.signInWithEmailAndPassword( emailController.text.trim(), passwordController.text.trim(), ); if (user != null) { // Navigate to home page } else { // Show error message } }, child: Text("Login"), ), ], ), ), ); } }
Step 6: Handle Authentication State
- Use a
StreamBuilder
to listen for authentication state changes and navigate users accordingly:StreamBuilder<User?>( stream: FirebaseAuth.instance.authStateChanges(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.active) { User? user = snapshot.data; if (user == null) { return LoginPage(); // Show login page } return HomePage(); // Show home page } return CircularProgressIndicator(); // Loading state }, )
Conclusion
You have now successfully implemented email and password authentication in your Flutter application using Firebase. You can further enhance this system by adding features like password reset, user registration, and profile management. The next steps could involve integrating the Firebase Realtime Database to manage doctor appointment data effectively. Happy coding!