Flutter Cloud Firestore Examples
Flutter Cloud Firestore How To Examples
Introduction
Cloud Firestore is a NoSQL document database provided by Firebase, which allows you to store and sync data in real-time between your Flutter app and the cloud. It is a powerful tool for managing and querying data, making it ideal for applications that require real-time updates.
In this tutorial, we will cover various examples of how to use Cloud Firestore in your Flutter app. We will start with the installation process and then dive into different scenarios where you can utilize Firestore to perform CRUD operations, query data, and listen for real-time updates.
Installation
To use Cloud Firestore in your Flutter app, you need to add the cloud_firestore
package as a dependency in your pubspec.yaml
file. Follow these steps to install the package:
Open your Flutter project in an editor.
Locate the
pubspec.yaml
file.Add
cloud_firestore
as a dependency under thedependencies
section.dependencies:
cloud_firestore: ^2.5.2Save the file and run
flutter pub get
in the terminal to fetch the package.
Now that you have the cloud_firestore
package installed, let's move on to the examples.
Example 1: Adding Data to Firestore
To add data to Firestore, you need to create an instance of FirebaseFirestore
and use the collection
method to specify the collection you want to add the data to. Here's an example that demonstrates how to add a document to a collection:
import 'package:cloud_firestore/cloud_firestore.dart';
void addData() {
FirebaseFirestore firestore = FirebaseFirestore.instance;
CollectionReference users = firestore.collection('users');
users
.add({'name': 'John', 'age': 25})
.then((value) => print('Data added successfully'))
.catchError((error) => print('Failed to add data: $error'));
}
In this example, we create a users
collection and add a document with the name and age fields. The add
method returns a Future<DocumentReference>
that you can use to handle success or failure.
Example 2: Updating Data in Firestore
To update data in Firestore, you can use the update
method on a DocumentReference
. Here's an example that demonstrates how to update a document:
import 'package:cloud_firestore/cloud_firestore.dart';
void updateData() {
FirebaseFirestore firestore = FirebaseFirestore.instance;
DocumentReference user =
firestore.collection('users').doc('document_id');
user
.update({'age': 26})
.then((value) => print('Data updated successfully'))
.catchError((error) => print('Failed to update data: $error'));
}
In this example, we retrieve a specific document using its ID and update the age field to 26 using the update
method.
Example 3: Deleting Data from Firestore
To delete data from Firestore, you can use the delete
method on a DocumentReference
. Here's an example that demonstrates how to delete a document:
import 'package:cloud_firestore/cloud_firestore.dart';
void deleteData() {
FirebaseFirestore firestore = FirebaseFirestore.instance;
DocumentReference user =
firestore.collection('users').doc('document_id');
user
.delete()
.then((value) => print('Data deleted successfully'))
.catchError((error) => print('Failed to delete data: $error'));
}
In this example, we retrieve a specific document using its ID and delete it using the delete
method.
Example 4: Querying Data from Firestore
To query data from Firestore, you can use the get
method on a CollectionReference
. Here's an example that demonstrates how to query documents based on a specific condition:
import 'package:cloud_firestore/cloud_firestore.dart';
void queryData() {
FirebaseFirestore firestore = FirebaseFirestore.instance;
CollectionReference users = firestore.collection('users');
users
.where('age', isGreaterThan: 20)
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
print(doc.data());
});
})
.catchError((error) => print('Failed to query data: $error'));
}
In this example, we query the users
collection to retrieve documents where the age field is greater than 20. The get
method returns a Future<QuerySnapshot>
which contains the query results. We iterate over the documents using the forEach
method and print the data.
Example 5: Real-time Data Updates with Firestore
Firestore provides real-time updates, allowing you to listen for changes in your data. Here's an example that demonstrates how to listen for real-time updates on a document:
import 'package:cloud_firestore/cloud_firestore.dart';
void listenForUpdates() {
FirebaseFirestore firestore = FirebaseFirestore.instance;
DocumentReference user =
firestore.collection('users').doc('document_id');
user.snapshots().listen((DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists) {
print(documentSnapshot.data());
} else {
print('Document does not exist');
}
});
}
In this example, we use the snapshots
method on a DocumentReference
to listen for changes in the document. The listen
method provides a stream of DocumentSnapshot
objects that you can handle in real-time.
Conclusion
In this tutorial, we covered various examples of how to use Cloud Firestore in your Flutter app. We explored adding, updating, and deleting data, querying data based on conditions, and listening for real-time updates. Cloud Firestore provides a powerful and flexible solution for managing data in your app, enabling real-time synchronization between devices and the cloud.