In this next step of your Flutter journey, we’ll focus on integrating Firebase into your app. Firebase is a powerful backend-as-a-service platform that offers a wide range of tools and services, such as real-time databases, authentication, cloud storage, and more. Firebase integration allows your Flutter apps to have cloud features without the need to set up a custom backend.
In this tutorial, we’ll go through the steps to set up Firebase for your Flutter app and demonstrate how to use Firebase Authentication and Cloud Firestore to manage user sign-ins and store data.
Why Use Firebase with Flutter?
Firebase simplifies common backend tasks and is highly compatible with Flutter. Here’s why it’s worth using:
- Authentication: Easily set up user authentication with email/password, Google, Facebook, and more.
- Realtime Database: Synchronize data in real-time across your app users.
- Firestore: A scalable, NoSQL cloud database perfect for structured data storage.
- Push Notifications: Keep your users engaged by sending them push notifications.
- Analytics: Get insights into how your app is being used with Firebase Analytics.
Setting Up Firebase in Your Flutter Project
1. Create a Firebase Project
Before you can integrate Firebase into your Flutter app, you need to create a Firebase project:
- Go to the Firebase Console.
- Click on Add Project.
- Follow the on-screen instructions to create a new project.
2. Add Firebase SDK to Your Flutter Project
Once the Firebase project is ready, you need to add Firebase to your Flutter project.
- Add Firebase to your Android app:
- Go to the Project Overview in the Firebase Console.
- Click on the Android icon to register your app.
- Download the
google-services.json
file and place it in theandroid/app
directory of your Flutter project.
- Add Firebase to your iOS app:
- Follow similar steps for iOS.
- Download the
GoogleService-Info.plist
file and place it in theios/Runner
directory. - For iOS, ensure your app uses Swift or Objective-C. Modify your
Podfile
to include Firebase dependencies.
3. Install Firebase Packages for Flutter
Now you’ll need to add Firebase packages to your Flutter project to start using Firebase services. Open pubspec.yaml
and add the following dependencies:
dependencies:
firebase_core: latest_version
firebase_auth: latest_version
cloud_firestore: latest_version
Run flutter pub get
to install these dependencies.
4. Initialize Firebase in Your Flutter App
To start using Firebase, initialize it in your app. In your main.dart
, modify the code to initialize Firebase before the app starts:
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(),
);
}
}
Now your Flutter app is ready to connect to Firebase.
Firebase Authentication: Adding User Sign-In
One of the most common features in modern apps is user authentication. Firebase makes it super easy to implement different methods of authentication, including email/password and third-party providers like Google and Facebook.
1. Setting Up Email and Password Authentication
In the Firebase Console, go to the Authentication section, click Get Started, and enable Email/Password sign-in under the Sign-In Method tab.
2. Creating a Sign-Up Screen in Flutter
Now let’s create a simple sign-up screen where users can create an account using their email and password. In your lib/
folder, create a new file called signup_screen.dart
.
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class SignUpScreen extends StatefulWidget {
@override
_SignUpScreenState createState() => _SignUpScreenState();
}
class _SignUpScreenState extends State<SignUpScreen> {
final FirebaseAuth _auth = FirebaseAuth.instance;
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
Future<void> _register() async {
try {
UserCredential userCredential = await _auth.createUserWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
);
print("User registered: ${userCredential.user?.email}");
} catch (e) {
print("Error: $e");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Sign Up"),
),
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: _register,
child: Text("Sign Up"),
),
],
),
),
);
}
}
This code creates a basic form where the user can enter their email and password. The _register() method uses Firebase Authentication to create a new user account.
3. Adding Sign-In Functionality
Next, let’s add a sign-in screen that allows users to log in with their email and password. Create a new file called login_screen.dart
:
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class LoginScreen extends StatefulWidget {
@override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final FirebaseAuth _auth = FirebaseAuth.instance;
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
Future<void> _login() async {
try {
UserCredential userCredential = await _auth.signInWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
);
print("User logged in: ${userCredential.user?.email}");
} catch (e) {
print("Error: $e");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Log In"),
),
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: _login,
child: Text("Log In"),
),
],
),
),
);
}
}
In this code, the _login() method allows users to sign in with their email and password.
Storing User Data in Cloud Firestore
Now that we have user authentication, let’s move on to storing user-related data in Cloud Firestore. Firestore is a NoSQL database that lets you store, sync, and query data in real-time.
1. Enabling Firestore in Firebase
In the Firebase Console, go to Firestore Database and click Create Database. Choose the starting mode and complete the setup.
2. Adding Firestore to Your Flutter App
In the pubspec.yaml
file, you already added the cloud_firestore
package. Now, let’s create a new screen where we can store and retrieve data from Firestore.
3. Writing Data to Firestore
Let’s create a screen where we add some data to Firestore. In your main.dart
or a new file:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class FirestoreScreen extends StatelessWidget {
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
Future<void> _addData() async {
await _firestore.collection("users").add({
"name": "John Doe",
"email": "johndoe@example.com",
});
print("User added to Firestore");
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Firestore Example"),
),
body: Center(
child: ElevatedButton(
onPressed: _addData,
child: Text("Add Data to Firestore"),
),
),
);
}
}
4. Reading Data from Firestore
To read data from Firestore, you can use the get() method to fetch documents:
Future<void> _getData() async {
QuerySnapshot querySnapshot = await _firestore.collection("users").get();
for (var doc in querySnapshot.docs) {
print(doc["name"]);
}
}
Conclusion: Firebase Powers Your App
By now, you’ve learned how to integrate Firebase into your Flutter app, enabling powerful backend functionality like
authentication and data storage. With Firebase, you can easily add more advanced features like push notifications, analytics, and real-time updates without needing to build your own backend.
In the next tutorial, we’ll dive deeper into Firebase Analytics and explore how you can track user behavior in your app to make data-driven decisions. Keep experimenting, and happy coding!