0
0
Fluttermobile~5 mins

Cloud Firestore CRUD in Flutter

Choose your learning style9 modes available
Introduction

Cloud Firestore lets your app save, read, update, and delete data in the cloud. This helps your app share data with users instantly and keep it safe.

You want to save user notes or messages online.
You need to show live updates to all users, like chat messages.
You want to keep user settings synced across devices.
You want to store app data without managing your own server.
You want to update or remove data easily from your app.
Syntax
Flutter
final docRef = FirebaseFirestore.instance.collection('collectionName').doc('docId');

// Create or update
await docRef.set({'field': 'value'});

// Read
final snapshot = await docRef.get();
final data = snapshot.data();

// Update
await docRef.update({'field': 'newValue'});

// Delete
await docRef.delete();

set() creates or replaces a document.

update() changes only specified fields.

Examples
This creates or replaces the 'user1' document with name and age.
Flutter
await FirebaseFirestore.instance.collection('users').doc('user1').set({'name': 'Alice', 'age': 25});
This reads the 'user1' document and prints its data.
Flutter
final snapshot = await FirebaseFirestore.instance.collection('users').doc('user1').get();
print(snapshot.data());
This updates only the age field of 'user1' document.
Flutter
await FirebaseFirestore.instance.collection('users').doc('user1').update({'age': 26});
This deletes the 'user1' document from the collection.
Flutter
await FirebaseFirestore.instance.collection('users').doc('user1').delete();
Sample App

This Flutter app shows buttons to add, update, get, and delete a user document in Firestore. The text updates to show the current action or data.

Flutter
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FirestoreDemo(),
    );
  }
}

class FirestoreDemo extends StatefulWidget {
  @override
  _FirestoreDemoState createState() => _FirestoreDemoState();
}

class _FirestoreDemoState extends State<FirestoreDemo> {
  final CollectionReference users = FirebaseFirestore.instance.collection('users');

  Future<void> addUser() async {
    await users.doc('user1').set({'name': 'Alice', 'age': 25});
  }

  Future<void> updateUser() async {
    await users.doc('user1').update({'age': 26});
  }

  Future<void> deleteUser() async {
    await users.doc('user1').delete();
  }

  Future<Map<String, dynamic>?> getUser() async {
    final doc = await users.doc('user1').get();
    return doc.exists ? doc.data() as Map<String, dynamic>? : null;
  }

  String displayText = 'No data';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Firestore CRUD Demo')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(displayText),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                await addUser();
                setState(() {
                  displayText = 'User added';
                });
              },
              child: Text('Add User'),
            ),
            ElevatedButton(
              onPressed: () async {
                await updateUser();
                setState(() {
                  displayText = 'User updated';
                });
              },
              child: Text('Update User'),
            ),
            ElevatedButton(
              onPressed: () async {
                final data = await getUser();
                setState(() {
                  displayText = data != null ? 'Name: ${data['name']}, Age: ${data['age']}' : 'User not found';
                });
              },
              child: Text('Get User'),
            ),
            ElevatedButton(
              onPressed: () async {
                await deleteUser();
                setState(() {
                  displayText = 'User deleted';
                });
              },
              child: Text('Delete User'),
            ),
          ],
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Make sure to initialize Firebase in your app before using Firestore.

Use set() to create or replace documents, and update() to change only some fields.

Always check if a document exists before reading its data to avoid errors.

Summary

Cloud Firestore stores app data in collections and documents.

CRUD means Create, Read, Update, and Delete data.

Flutter uses FirebaseFirestore.instance to access Firestore and perform these actions.