Flutter firestore example

Flutter Firestore Example

Firestore is a NoSQL cloud database provided by Firebase, which can be easily integrated with Flutter applications to store and sync data in real-time. Here is an example of how to use Firestore in a Flutter app:

1. Set up Firebase

Before using Firestore, make sure you have a Firebase project set up.

  • Go to the Firebase Console and create a new project.
  • Follow the instructions to add Firebase to your Flutter app. This typically involves adding the necessary dependencies to your pubspec.yaml file and downloading the GoogleServices-Info.plist/ google-services.json file.

2. Initialize Firestore

In your main.dart file, import the necessary packages:


    import 'package:cloud_firestore/cloud_firestore.dart';
  

Then, initialize Firestore in your main method:


    void main() {
      runApp(MyApp());
      
      // Initialize Firestore
      FirebaseFirestore.instance.settings = Settings(persistenceEnabled: true);
    }
  

3. CRUD Operations

Firestore allows you to perform CRUD (Create, Read, Update, Delete) operations on your data.

3.1. Create Data

To create a new document in a Firestore collection, use the `set()` method:


    CollectionReference usersCollection = FirebaseFirestore.instance.collection('users');
    
    void createUser(String name, int age) {
      usersCollection.add({'name': name, 'age': age});
    }
  

3.2. Read Data

To read data from Firestore, use the `get()` method to retrieve a single document, or the `snapshots()` method to listen for real-time updates:


    void readUser(String documentId) {
      usersCollection.doc(documentId).get().then((snapshot) {
        if (snapshot.exists) {
          print('Document data: ${snapshot.data()}');
        } else {
          print('Document does not exist');
        }
      });
    }
    
    void listenToUsers() {
      usersCollection.snapshots().listen((querySnapshot) {
        querySnapshot.docs.forEach((doc) {
          print('User: ${doc.data()}');
        });
      });
    }
  

3.3. Update Data

To update an existing document in Firestore, use the `update()` method:


    void updateUser(String documentId, String newName) {
      usersCollection.doc(documentId).update({'name': newName});
    }
  

3.4. Delete Data

To delete a document from Firestore, use the `delete()` method:


    void deleteUser(String documentId) {
      usersCollection.doc(documentId).delete();
    }
  

4. Querying Data

Firestore also supports querying documents based on certain conditions:


    void queryUsersAboveAge(int age) {
      usersCollection.where('age', isGreaterThanOrEqualTo: age).get().then((querySnapshot) {
        querySnapshot.docs.forEach((doc) {
          print('User above age $age: ${doc.data()}');
        });
      });
    }
  

5. Wrapping Up

Firestore offers many more features like data modeling, security rules, and offline capabilities, which you can explore in the official documentation.

By following the above steps and examples, you can start integrating Firestore into your Flutter app and leverage its powerful real-time database capabilities.

Leave a comment