Flutter SQLite CRUD Example — Learn Local Database with Ease
Introduction
When building Flutter apps, sometimes you don’t need a cloud database like Firebase. Instead, a local lightweight database is enough — for example, when storing notes, tasks, or offline data. Flutter provides an easy way to work with SQLite using the sqflite plugin.
In this post, we’ll walk through a working SQLite CRUD (Create, Read, Update, Delete) example taken from my GitHub repo: SQL-Lite.
Keywords
Flutter SQLite, Flutter local database, sqflite CRUD, SQLite in Flutter, DatabaseHandler Flutter
Importance
- Works offline — perfect for apps that don’t always have internet.
- Lightweight yet powerful.
- Easy to integrate with Flutter using the sqflite package.
- Supports structured queries, making it great for CRUD-based apps.
👉 Contact on WhatsApp
Explanation
1. The Model — book.dart
class Book {
int? id;
String name;
double price;
Book({this.id, required this.name, required this.price});
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'price': price,
};
}
@override
String toString() {
return 'Book{id: $id, name: $name, price: $price}';
}
}
2. Database Handler — databasehandler.dart
class DatabaseHandler {
static Future<Database> initialize() async {
final dbPath = await getDatabasesPath();
return openDatabase(
join(dbPath, 'books.db'),
onCreate: (db, version) {
return db.execute(
'CREATE TABLE books(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, price REAL)',
);
},
version: 1,
);
}
Future<int> insertBook(Book book) async {
final db = await initialize();
return await db.insert('books', book.toMap());
}
Future<List<Book>> books() async {
final db = await initialize();
final List<Map<String, dynamic>> maps = await db.query('books');
return List.generate(maps.length, (i) {
return Book(
id: maps[i]['id'],
name: maps[i]['name'],
price: maps[i]['price'],
);
});
}
}
3. The UI — vsjsqlite.dart
The app uses a simple Flutter UI with buttons and text fields. You can add a book, view the list, update, or delete it.
4. Entry Point — main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await DatabaseHandler.initialize();
runApp(MyApp());
}
New: DartPad (web) version — using localStorage
This single-file Flutter app runs in DartPad (Flutter) and uses the browser localStorage for persistence.
Copy the code below and paste it into DartPad (choose Flutter), then press Run.
// Paste this entire file into DartPad (Flutter) and run.
// Uses browser localStorage to store a list of books as JSON.
// Works only in Flutter web (DartPad Flutter).
import 'dart:convert';
import 'dart:html' as html; // for localStorage
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
/// Keys used in localStorage
const String storageKey = 'vsj_books';
/// Simple Book model
class Book {
int? id; // generated client-side
String name;
double price;
Book({this.id, required this.name, required this.price});
Map toMap() => {
'id': id,
'name': name,
'price': price,
};
factory Book.fromMap(Map m) => Book(
id: m['id'] as int?,
name: m['name'] as String? ?? '',
price: (m['price'] is int)
? (m['price'] as int).toDouble()
: (m['price'] as double? ?? 0.0),
);
@override
String toString() => 'Book{id: $id, name: $name, price: $price}';
}
/// Simple storage wrapper using browser localStorage
class LocalBookStorage {
/// Read all books
static List readAll() {
final raw = html.window.localStorage[storageKey];
if (raw == null) return [];
try {
final List list = jsonDecode(raw) as List;
final books = list
.map((e) => Book.fromMap(Map.from(e)))
.toList();
return books;
} catch (e) {
// If parsing fails, return empty and reset storage to avoid repeated errors
html.window.localStorage.remove(storageKey);
return [];
}
}
/// Write the full list
static void writeAll(List books) {
final List
Tip: After copying, open DartPad (choose the Flutter pad), paste the code into main.dart, and press Run.
Complexity
The DartPad/localStorage example uses simple JSON read/write:
- Insert / Update / Delete — O(1) average per item
- Read all — O(n) where n is number of books
How to Run
git clone https://github.com/Varanasi-Software-Junction/SQL-Lite.git
cd SQL-Lite
flutter pub get
flutter run
Conclusion
SQLite is great for mobile apps; for quick web demos DartPad + localStorage is simpler. Both approaches show the same CRUD flow and help you get a working app fast.
- ⭐ Star the repo on GitHub: SQL-Lite
- ⬇️ Download Project (ZIP)
- 💬 Need help? Contact on WhatsApp
0 Comments