Flutter Firebase CRUD: A Complete Guide to Realtime Database Operations (with Tutorial)

In today’s mobile-first world, building apps that sync data in real time is essential. Flutter, Google’s UI toolkit for building natively compiled applications, pairs beautifully with Firebase, Google’s mobile and web application development platform. Together, they enable developers to create powerful, scalable apps with minimal backend effort.

In this in-depth guide, we’ll walk through CRUD operations (Create, Read, Update, Delete) using Flutter and Firebase Realtime Database. Whether you’re building a simple note-taking app or a real-time chat system, this tutorial will give you the foundation you need.


πŸ” Why Use Firebase with Flutter?

Before diving into code, let’s understand why this combination is so popular:

  • No backend required: Firebase handles authentication, storage, and database logic.
  • Realtime synchronization: Data updates instantly across all connected devices.
  • Easy integration: The firebase_core and firebase_database packages make setup a breeze.
  • Free tier available: Great for prototyping and small-scale apps.

This makes Flutter + Firebase ideal for rapid development of realtime CRUD applications.


πŸ“š What Is CRUD?

CRUD stands for:

OperationDescription
CreateAdd new data to the database
ReadRetrieve data from the database
UpdateModify existing data
DeleteRemove data from the database

We’ll implement each of these using Firebase Realtime Database in a Flutter app.


πŸ› οΈ Prerequisites

Before we begin, ensure you have:

  1. Flutter SDK installed
  2. Android Studio / VS Code with Flutter plugin
  3. A Firebase account (free at https://firebase.google.com)
  4. Basic knowledge of Dart and Flutter widgets

🧩 Step 1: Set Up Firebase Project

  1. Go to the Firebase Console
  2. Click “Add Project”, name it (e.g., flutter-crud-app)
  3. Enable Realtime Database
  • Choose test mode for development (lock rules to allow read/write)
  1. Register your app (Android/iOS/Web)
  2. Download google-services.json (Android) or GoogleService-Info.plist (iOS)
  3. Place the config file in your Flutter project (android/app/ for Android)

πŸ“¦ Step 2: Add Firebase Dependencies

In your pubspec.yaml, add:

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^2.24.0
  firebase_database: ^10.5.5

Then run:

flutter pub get

πŸ’‘ Tip: Always check pub.dev for the latest versions of firebase_core and firebase_database.


πŸ” Step 3: Initialize Firebase

In your main.dart, initialize Firebase before running the app:

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Firebase CRUD',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const CrudScreen(),
    );
  }
}

πŸ—‚οΈ Step 4: Design Your Data Structure

Let’s build a simple Task Manager App. Each task will have:

{
  "taskId": {
    "title": "Learn Flutter",
    "description": "Build a CRUD app with Firebase",
    "createdAt": "2025-04-05"
  }
}

Data will be stored under /tasks in the Realtime Database.


βœ… Step 5: Implement CRUD Operations

Create a new file: crud_screen.dart

πŸ”Ή 1. Create – Add a New Task

final ref = FirebaseDatabase.instance.ref().child('tasks');

void addTask(String title, String description) {
  String taskId = const Uuid().v4(); // Use uuid package
  ref.child(taskId).set({
    'title': title,
    'description': description,
    'createdAt': DateTime.now().toString(),
  });
}

πŸ’‘ Install uuid: ^4.0.0 for generating unique IDs.

πŸ”Ή 2. Read – Fetch All Tasks

Use a StreamBuilder to listen to real-time updates:

StreamBuilder<DatabaseEvent>(
  stream: ref.onValue,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      Map<dynamic, dynamic>? tasks = snapshot.data?.snapshot.value as Map?;
      List<Task> taskList = [];

      if (tasks != null) {
        taskList = tasks.entries.map((entry) {
          var data = entry.value as Map<dynamic, dynamic>;
          return Task(
            id: entry.key,
            title: data['title'],
            description: data['description'],
            createdAt: data['createdAt'],
          );
        }).toList();
      }

      return ListView.builder(
        itemCount: taskList.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(taskList[index].title),
            subtitle: Text(taskList[index].description),
            trailing: IconButton(
              icon: const Icon(Icons.delete),
              onPressed: () => deleteTask(taskList[index].id!),
            ),
          );
        },
      );
    } else {
      return const Center(child: CircularProgressIndicator());
    }
  },
)

πŸ”Ή 3. Update – Edit an Existing Task

void updateTask(String taskId, String newTitle, String newDescription) {
  ref.child(taskId).update({
    'title': newTitle,
    'description': newDescription,
  });
}

πŸ”Ή 4. Delete – Remove a Task

void deleteTask(String taskId) {
  ref.child(taskId).remove();
}

πŸ–ΌοΈ Step 6: Build the UI

Here’s a minimal UI to demonstrate all operations:

class CrudScreen extends StatefulWidget {
  const CrudScreen({super.key});

  @override
  State<CrudScreen> createState() => _CrudScreenState();
}

class _CrudScreenState extends State<CrudScreen> {
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _descController = TextEditingController();

  void _addTask() {
    if (_titleController.text.isNotEmpty) {
      addTask(_titleController.text, _descController.text);
      _titleController.clear();
      _descController.clear();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Flutter Firebase CRUD")),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              children: [
                TextField(controller: _titleController, decoration: const InputDecoration(labelText: "Title")),
                TextField(controller: _descController, decoration: const InputDecoration(labelText: "Description")),
                ElevatedButton(onPressed: _addTask, child: const Text("Add Task")),
              ],
            ),
          ),
          Expanded(child: _buildTaskList()), // StreamBuilder from earlier
        ],
      ),
    );
  }
}

🌐 Flutter Web: Realtime Database Support

Yes! Firebase Realtime Database works perfectly with Flutter Web. Just make sure:

  • You enable the web app in Firebase Console
  • Include the Firebase SDK snippet in your index.html
  • Use the same Dart code β€” it’s cross-platform!

πŸ”— Learn more: flutter web realtime database – this setup allows your app to run seamlessly on Android, iOS, and Web with shared logic.


πŸš€ Tips for Production

  • Secure your database: Update Firebase rules to restrict access:
  {
    "rules": {
      "tasks": {
        ".read": "auth != null",
        ".write": "auth != null"
      }
    }
  }
  • Use Firebase Authentication to identify users.
  • Consider Cloud Firestore for complex queries (though Realtime DB is faster for simple sync).
  • Handle errors with try-catch and show user feedback.

These keywords have varying search volumes and competition, but combining tutorial-style content with real code examples increases visibility and engagement.

πŸ”Ž Pro Tip: Use long-tail keywords like “how to do crud in flutter with firebase” or “realtime database flutter example” in headings and meta descriptions.


πŸ“š Additional Resources


πŸŽ‰ Conclusion

Building a Flutter Firebase CRUD app with Realtime Database is fast, efficient, and scalable. With just a few lines of code, you can create apps that sync data instantly across devices β€” perfect for chat apps, task managers, live trackers, and more.

By mastering CRUD operations, you unlock the full potential of backend-less app development. Whether you’re a beginner or an experienced developer, this stack offers a smooth learning curve and powerful results.


❓ Frequently Asked Questions (FAQ)

Q: Can I use Firebase Realtime Database offline in Flutter?
A: Yes! Firebase supports offline persistence. Enable it with:

await FirebaseDatabase.instance.setPersistenceEnabled(true);

Q: How do I delete a Firebase project?
A: Go to Firebase Console β†’ Project Settings β†’ Scroll to bottom β†’ Delete Project.

Q: Is Realtime Database free?
A: Yes, within usage limits (1 GB storage, 10 GB/month download).

Q: What’s the difference between Firestore and Realtime Database?
A: Firestore offers better querying and scalability; Realtime DB is simpler and faster for small, synced datasets.


πŸ“£ Your Turn!

Now that you’ve learned how to perform CRUD operations in Flutter with Firebase, try extending the app:

  • Add user authentication
  • Implement search/filter
  • Show real-time edit indicators
  • Deploy to web using flutter build web

Drop your questions or project ideas in the comments below πŸ‘‡

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.