Firebase is a comprehensive mobile and web development platform provided by Google. Firebase provides developers with a suite of tools and services to develop and deploy high-quality mobile and web applications quickly and easily. Firebase offers many features such as authentication, real-time database, cloud messaging, and many more, making it an excellent choice for building modern and scalable mobile and web applications.
Flutter is a popular open-source framework for building cross-platform mobile applications. Flutter offers a rich set of widgets and tools to create beautiful and high-performance mobile applications quickly and easily. Flutter integrates seamlessly with Firebase, making it an excellent choice for building modern and scalable mobile applications.
In this blog, we will explore how to use Firebase with Flutter to build a mobile application with authentication and a real-time database.
Setting up Firebase in Flutter project
Before we can start using Firebase with Flutter, we need to set up a Firebase project and add Firebase to our Flutter project. Here are the steps to set up a Firebase project:
Go to the Firebase console (https://console.firebase.google.com/) and create a new project.
Give your project a name and select your country or region.
Click on "Create Project."
After the project is created, click on "Add Firebase to your Android app" or "Add Firebase to your iOS app," depending on which platform you are developing for. Follow the instructions to add Firebase to your project.
Run the following code to install Firebase core.
flutter pub add firebase_core
Once we have set up our Firebase project and added Firebase to our Flutter project, we can start using Firebase in our application.
Authentication with Firebase
Firebase offers many authentication methods such as email and password, Google, Facebook, Twitter, and many more. In this blog, we will focus on email and password authentication.
To use email and password authentication with Firebase, we need to add the following dependencies to our Flutter project:
flutter pub add firebase_auth
After adding the dependency, we can use the following code to create a new user:
import 'package:firebase_auth/firebase_auth.dart';
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<String> createUserWithEmailAndPassword(String email, String password) async {
try {
UserCredential userCredential = await _auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
return "success";
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
return 'The password provided is too weak.';
} else if (e.code == 'email-already-in-use') {
return 'The account already exists for that email.';
}
return e.message;
} catch (e) {
return e.toString();
}
}
In the above code, we first import the firebase_auth package and create an instance of FirebaseAuth. We then define a function createUserWithEmailAndPassword that takes an email and password as arguments and returns a Future<String>. Inside the function, we call the createUserWithEmailAndPassword method on the FirebaseAuth instance, passing in the email and password. If the user is created successfully, we return "success". If an error occurs, we return a message indicating the reason for the error.
We can use the following code to sign in a user:
import 'package:firebase_auth/firebase_auth.dart';
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<String> signInWithEmailAndPassword(String email, String password) async {
try {
UserCredential userCredential = await _auth.signInWithEmailAndPassword(
email: email,
password: password,
);
return "success";
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
return 'No user found for that email.';
} else if (e.code == 'wrong-password') {
return 'Wrong password provided for that user.';
}
return e.message;
} catch (e) {
return e.toString();
}
}
In the above code, we define a function `signInWithEmailAndPassword` that takes an email and password as arguments and returns a `Future<String>`. Inside the function, we call the `signInWithEmailAndPassword` method on the `FirebaseAuth` instance, passing in the email and password. If the sign-in is successful, we return "success". If an error occurs, we return a message indicating the reason for the error.
We can use the following code to sign out a user:
import 'package:firebase_auth/firebase_auth.dart';
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<void> signOut() async {
await _auth.signOut();
}
In the above code, we define a function signOut that does not take any arguments and returns a Future<void>. Inside the function, we call the signOut method on the FirebaseAuth instance to sign out the current user.
Realtime Database with Firebase
Firebase Realtime Database is a cloud-hosted database that stores data in JSON format. Firebase Realtime Database offers real-time synchronization, offline support, and automatic conflict resolution, making it an excellent choice for building real-time applications.
To use Firebase Realtime Database with Flutter, we need to add the following dependencies to our Flutter project:
flutter pub add firebase_database
After adding the dependency, we can use the following code to read data from the database:
import 'package:firebase_database/firebase_database.dart';
final DatabaseReference _database = FirebaseDatabase.instance.reference();
Future<String> readData() async {
try {
DataSnapshot dataSnapshot = await _database.child("path/to/data").once();
return dataSnapshot.value;
} catch (e) {
return e.toString();
}
}
In the above code, we first import the firebase_database package and create an instance of FirebaseDatabase. We then define a function readData that returns a Future<String>. Inside the function, we call the once method on the reference to the data we want to read from, which returns a DataSnapshot. We can access the value of the DataSnapshot using the value property.
We can use the following code to write data to the database:
import 'package:firebase_database/firebase_database.dart';
final DatabaseReference _database = FirebaseDatabase.instance.reference();
Future<String> writeData(String data) async {
try {
await _database.child("path/to/data").set(data);
return "success";
} catch (e) {
return e.toString();
}
}
In the above code, we define a function writeData that takes a string data as an argument and returns a Future<String>. Inside the function, we call the set method on the reference to the data we want to write to, passing in the data. If the write is successful, we return "success". If an error occurs, we return a message indicating the reason for the error.
Conclusion
Firebase offers many features that make it an excellent choice for building modern and scalable mobile and web applications. In this blog, we explored how to use Firebase with Flutter to build a mobile application with authentication and a real-time database. We covered how to set up a Firebase project, authenticate users using email and password, and read and write data to the real-time database. By combining the power of Firebase and Flutter, we can build high-quality mobile applications quickly and easily.