Learn how to implement sign-in and sign-up functionalities using Firebase Authentication in Flutter, including email/password and Google Sign-In methods.
In this section, we will explore how to implement sign-in and sign-up functionalities in a Flutter application using Firebase Authentication. We will cover both email/password authentication and third-party authentication using Google Sign-In. By the end of this guide, you will be able to integrate these authentication methods into your Flutter app, providing a seamless user experience.
firebase_auth
to Your ProjectTo begin, you need to add the firebase_auth
package to your Flutter project. This package provides the necessary tools to implement authentication features.
Open your pubspec.yaml
file and add the firebase_auth
dependency:
dependencies:
firebase_auth: ^3.0.0
Run the following command to install the package:
flutter pub get
This will download and integrate the firebase_auth
package into your project, allowing you to use Firebase Authentication services.
Implementing email and password sign-up involves creating a user interface for input and handling the authentication logic.
First, let’s create a simple sign-up form using TextFormField
widgets for email and password inputs. Ensure that you include validation to enhance user experience and data integrity.
import 'package:flutter/material.dart';
class SignUpForm extends StatefulWidget {
@override
_SignUpFormState createState() => _SignUpFormState();
}
class _SignUpFormState extends State<SignUpForm> {
final _formKey = GlobalKey<FormState>();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: _emailController,
decoration: InputDecoration(labelText: 'Email'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your email';
}
if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) {
return 'Enter a valid email';
}
return null;
},
),
TextFormField(
controller: _passwordController,
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your password';
}
if (value.length < 6) {
return 'Password must be at least 6 characters long';
}
return null;
},
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
// Proceed with sign-up
signUpWithEmail(_emailController.text, _passwordController.text);
}
},
child: Text('Sign Up'),
),
],
),
);
}
Future<void> signUpWithEmail(String email, String password) async {
// Sign-up logic will be implemented here
}
}
Now, let’s implement the sign-up logic using Firebase Authentication. This involves creating a new user with the provided email and password.
import 'package:firebase_auth/firebase_auth.dart';
Future<void> signUpWithEmail(String email, String password) async {
try {
UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email,
password: password,
);
// Navigate to home screen or display success message
print('Sign-up successful!');
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('An account already exists for that email.');
}
} catch (e) {
print(e);
}
}
Explanation:
The sign-in process is similar to sign-up, but it involves authenticating existing users.
Implement the sign-in logic using Firebase Authentication:
Future<void> signInWithEmail(String email, String password) async {
try {
UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email,
password: password,
);
// Navigate to home screen or display success message
print('Sign-in successful!');
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
print('No user found for that email.');
} else if (e.code == 'wrong-password') {
print('Wrong password provided.');
}
}
}
Explanation:
print
, consider using SnackBar
or dialog boxes to inform users about the authentication status.In addition to email/password authentication, you can offer users the option to sign in using their Google account.
Add the google_sign_in
package to your pubspec.yaml
:
dependencies:
google_sign_in: ^5.0.0
Implement the Google Sign-In flow:
import 'package:google_sign_in/google_sign_in.dart';
Future<void> signInWithGoogle() async {
final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
if (googleUser == null) {
// The user canceled the sign-in
return;
}
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
await FirebaseAuth.instance.signInWithCredential(credential);
// Navigate to home screen or display success message
print('Google Sign-in successful!');
}
Platform-Specific Configurations:
android/app/google-services.json
file and updated your AndroidManifest.xml
with the necessary permissions and metadata.ios/Runner/Info.plist
with the required configurations and ensure you have the correct GoogleService-Info.plist
file.SnackBar
or dialogs instead of console prints.Implementing sign-in and sign-up functionalities using Firebase Authentication in Flutter is a powerful way to manage user authentication in your app. By following the steps outlined in this guide, you can provide a secure and user-friendly authentication experience. Remember to handle errors gracefully and provide meaningful feedback to users. With these skills, you can enhance your app’s functionality and improve user engagement.