Let's get started with the step-by-step process of integrating Firebase Authentication with email and password in a Flutter project.
Step 1: Set up Firebase Authentication in Firebase Console
- Navigate to the Firebase Console (console.firebase.google.com) and select your project.
- Go to the "Authentication" section from the left-hand menu.
- Click on the "Sign-in method" tab.
- Enable the "Email/Password" provider.
Step 2: Configure Flutter project for Firebase Authentication
- Ensure you have added the necessary dependencies in your Flutter project's
pubspec.yaml
file:
yamldependencies:
firebase_core: ^1.3.0
firebase_auth: ^3.1.0
- Run
flutter pub get
in the terminal to download the packages.
Step 3: Initialize Firebase in your Flutter app
- Import the required packages in your
main.dart
file:
dartimport 'package:firebase_core/firebase_core.dart';
- Inside your
main()
function, initialize Firebase:
dartvoid main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); }
Step 4: Implement Email and Password Sign-up
Create a new Dart file, such assignup_screen.dart
.Import the required packages:
Step 6: Implement Email and Password Sign-in (similar to Step 4)dartimport 'package:firebase_auth/firebase_auth.dart';
- Create a new Dart file, such as
loginpage.dart,userhomepage.dart
. - Import the required packages and modify the code accordingly.
- Add a route for the sign-in screen in
main.dart
.
FULL SOURCE CODE :
FOLDER STRUCTURE :
main.dart code
<!-- main.dart --> import 'package:firebaseauthsample/screens/loginpage.dart'; import 'package:firebaseauthsample/screens/userhomepage.dart'; import 'package:flutter/material.dart'; import 'package:firebase_core/firebase_core.dart'; import 'firebase_options.dart'; import 'package:firebase_auth/firebase_auth.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); runApp(MyApp()); } class MyApp extends StatelessWidget { MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(useMaterial3: true), title: 'firebase auth example', home: StreamBuilder<User?>( stream: FirebaseAuth.instance.authStateChanges(), builder: (context, snapshot) { if (snapshot.hasData) { return userhomepage(); } else { return loginpage(); } }, )); } }
<!-- loginpage.dart -->
// import 'package:firebaseauthsample/screens/userloginpage.dart'; import 'package:firebaseauthsample/screens/userhomepage.dart'; import 'package:flutter/material.dart'; import 'package:firebase_auth/firebase_auth.dart'; class loginpage extends StatefulWidget { loginpage({super.key}); @override State<loginpage> createState() => _loginpageState(); } class _loginpageState extends State<loginpage> { TextEditingController emailController = TextEditingController(); TextEditingController passwordController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, title: const Text('firebaseauth login/signup')), body: Padding( padding: const EdgeInsets.all(8.0), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextField( controller: emailController, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Email', ), ), const SizedBox(height: 10), TextField( controller: passwordController, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Password', ), ), const SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( onPressed: () async { try { UserCredential userCredential = await FirebaseAuth .instance .signInWithEmailAndPassword( email: emailController.text, password: passwordController.text, ); User? user = userCredential.user; print('Signed in: ${user!.uid}'); Navigator.push( context, MaterialPageRoute( builder: (context) => const userhomepage())); } catch (e) { print('Sign-in error: $e'); } }, child: const Text('Sign in'), ), const SizedBox(width: 10), ElevatedButton( onPressed: () async { await FirebaseAuth.instance .createUserWithEmailAndPassword( email: emailController.text, password: passwordController.text, ); }, child: const Text('Sign up'), ), ], ), ], ), ), ), ); } }
<!-- userhomepage.dart -->
import 'package:firebaseauthsample/screens/loginpage.dart'; import 'package:flutter/material.dart'; import 'package:firebase_auth/firebase_auth.dart'; class userhomepage extends StatefulWidget { const userhomepage({super.key}); @override State<userhomepage> createState() => _userhomepageState(); } class _userhomepageState extends State<userhomepage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, title: Text('User Home Page')), body: Padding( padding: const EdgeInsets.all(8.0), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ const SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( onPressed: () async { await FirebaseAuth.instance.signOut(); Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => loginpage())); }, child: Text('Sign out'), ), ], ), ], ), ), ), ); } }
Congratulations! You have successfully implemented Firebase Authentication with email and password in your Flutter app. Users can now sign up and sign in securely using their email addresses and passwords. Firebase Authentication simplifies the authentication process, providing a robust and scalable solution for managing user accounts.
Remember to handle any errors or exceptions that may occur during authentication and tailor the user experience accordingly. You can explore additional features offered by Firebase Authentication, such as integrating social media login options or customizing user profiles.
Firebase continues to be a powerful suite of tools that enables developers to build feature-rich applications quickly. We hope this blog post helps you leverage the capabilities of Firebase Authentication to enhance the security and user experience of your Flutter