Hello, Flutter developers! In this tutorial, we will explore in detail how to set up user authentication via Email using Firebase. Firebase offers a variety of services including databases, hosting, storage, and particularly Firebase Auth, which is very useful for handling user authentication. In this tutorial, we will guide you step-by-step on how to install the Firebase Auth package and set up email authentication.
1. Create a Firebase Project
To use Firebase, you first need to create a project in the Firebase console. Follow the steps below to create a project.
- Access the Firebase console.
- Click the ‘Add Project’ button in the top right corner.
- Enter the project name, select the Google Analytics settings, and then click ‘Create Project’.
2. Set up Firebase Auth
Once the project is created, you need to set up Firebase Auth.
- Click on ‘Authentication’ in the left menu.
- Navigate to the ‘Sign-in method’ tab.
- Find and enable the Email/Password sign-in option.
3. Create a Flutter Project
Now, let’s create a Flutter project. Use the command below to create a new Flutter project.
flutter create firebase_auth_example
Navigate to the project directory.
cd firebase_auth_example
4. Install Firebase Core and Auth Packages
You need to add the necessary packages to use Firebase in Flutter. Open the ‘pubspec.yaml’ file and add the following dependencies.
dependencies:
flutter:
sdk: flutter
firebase_core: ^2.0.0
firebase_auth: ^5.0.0
Now, enter the command below to install the packages.
flutter pub get
5. Initialize Firebase
After installing the packages, you need to initialize Firebase. Open the ‘main.dart’ file and add the following code.
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Firebase Auth Example',
home: HomeScreen(),
);
}
}
6. Create Login UI
Let’s build a login screen for email authentication. Add the ‘HomeScreen’ widget and include fields for email and password input as well as a login button.
import 'package:firebase_auth/firebase_auth.dart';
// ...
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State {
final FirebaseAuth _auth = FirebaseAuth.instance;
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
void signIn(String email, String password) async {
try {
UserCredential userCredential = await _auth.signInWithEmailAndPassword(
email: email,
password: password,
);
print('User signed in: ${userCredential.user}');
} on FirebaseAuthException catch (e) {
print('Failed to sign in: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Login'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: _emailController,
decoration: InputDecoration(labelText: 'Email'),
),
TextField(
controller: _passwordController,
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
signIn(_emailController.text, _passwordController.text);
},
child: Text('Login'),
),
],
),
),
);
}
}
7. Request Email Verification
After signing in, the user can request email verification. Add the code as below.
void sendVerificationEmail(User user) async {
if (!user.emailVerified) {
await user.sendEmailVerification();
print('Verification email sent to ${user.email}');
}
}
// Add this at the end of the signIn method.
if (userCredential.user != null) {
sendVerificationEmail(userCredential.user!);
}
8. Check Email Verification
Add logic to check if the user has verified their email. You can verify whether the user checked their email after logging in.
void checkEmailVerification() async {
User? user = _auth.currentUser;
await user?.reload();
user = _auth.currentUser;
if (user != null && user.emailVerified) {
print('Email verified!');
// Logic to navigate as a verified user can be added.
} else {
print('Email not verified yet.');
}
}
// Add at the end of the signIn method.
checkEmailVerification();
9. Complete Code
Finally, the complete main.dart
code is as follows.
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Firebase Auth Example',
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State {
final FirebaseAuth _auth = FirebaseAuth.instance;
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
void signIn(String email, String password) async {
try {
UserCredential userCredential = await _auth.signInWithEmailAndPassword(
email: email,
password: password,
);
sendVerificationEmail(userCredential.user!);
checkEmailVerification();
} on FirebaseAuthException catch (e) {
print('Failed to sign in: $e');
}
}
void sendVerificationEmail(User user) async {
if (!user.emailVerified) {
await user.sendEmailVerification();
print('Verification email sent to ${user.email}');
}
}
void checkEmailVerification() async {
User? user = _auth.currentUser;
await user?.reload();
user = _auth.currentUser;
if (user != null && user.emailVerified) {
print('Email verified!');
} else {
print('Email not verified yet.');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Login'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: _emailController,
decoration: InputDecoration(labelText: 'Email'),
),
TextField(
controller: _passwordController,
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
signIn(_emailController.text, _passwordController.text);
},
child: Text('Login'),
),
],
),
),
);
}
}
10. Conclusion
Now you have learned how to set up email authentication using Flutter and Firebase. Requesting email verification is an important feature to enhance user experience. Please utilize this feature for additional security. In the next tutorial, we will cover how to implement social login. Thank you!