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
andfirebase_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:
Operation | Description |
---|---|
Create | Add new data to the database |
Read | Retrieve data from the database |
Update | Modify existing data |
Delete | Remove 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:
- Flutter SDK installed
- Android Studio / VS Code with Flutter plugin
- A Firebase account (free at https://firebase.google.com)
- Basic knowledge of Dart and Flutter widgets
π§© Step 1: Set Up Firebase Project
- Go to the Firebase Console
- Click “Add Project”, name it (e.g.,
flutter-crud-app
) - Enable Realtime Database
- Choose test mode for development (lock rules to allow read/write)
- Register your app (Android/iOS/Web)
- Download
google-services.json
(Android) orGoogleService-Info.plist
(iOS) - 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
andfirebase_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
- Firebase Realtime Database Documentation
- FlutterFire Docs
- Flutter CRUD App Tutorial (YouTube)
- Using Firebase with Flutter Web
π 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 π