Question #190MediumOOP Concepts

What are all the local database i have worked on ? (SQL) - SQLite , (No SQL) - Sembast , objectbox

#database

Answer

Overview

Flutter supports multiple local database solutions for storing data on the device without an internet connection. They fall into two main categories: SQL (relational) and NoSQL (non-relational).


Local Databases Overview

DatabaseTypeLanguageBest For
SQLite (sqflite)SQL / RelationalSQL queriesStructured data with relationships
Drift (moor)SQL ORMType-safe DartSQL with Dart-friendly API
SembastNoSQL (Document)DartSimple JSON-like local storage
HiveNoSQL (Key-Value)DartFast, lightweight storage
IsarNoSQL (Object DB)DartHigh-performance full-featured local DB
ObjectBoxNoSQL (Object DB)DartVery fast, object-oriented storage
Shared PreferencesKey-ValueDartSimple settings and config only

1. SQLite — sqflite (SQL)

The most commonly used relational local database in Flutter.

dart
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class DatabaseHelper {
  static Database? _db;

  Future<Database> get database async {
    _db ??= await _initialize();
    return _db!;
  }

  Future<Database> _initialize() async {
    final path = join(await getDatabasesPath(), 'app.db');
    return await openDatabase(
      path,
      version: 1,
      onCreate: (db, version) async {
        await db.execute('''
          CREATE TABLE notes (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            body TEXT
          )
        ''');
      },
    );
  }

  // CRUD
  Future<int> insertNote(Map<String, dynamic> note) async {
    final db = await database;
    return db.insert('notes', note);
  }

  Future<List<Map<String, dynamic>>> getNotes() async {
    final db = await database;
    return db.query('notes');
  }

  Future<int> deleteNote(int id) async {
    final db = await database;
    return db.delete('notes', where: 'id = ?', whereArgs: [id]);
  }
}

When to use: Structured data with relationships, complex SQL queries, proven technology.


2. Sembast (NoSQL — Document Store)

A simple, pure-Dart NoSQL database. Great for simple local storage without the overhead of SQL.

dart
import 'package:sembast/sembast.dart';
import 'package:sembast/sembast_io.dart';
import 'package:path_provider/path_provider.dart';

class SembastHelper {
  static Database? _db;
  final _store = StoreRef<int, Map<String, Object?>>.main();

  Future<Database> get database async {
    if (_db != null) return _db!;
    final dir = await getApplicationDocumentsDirectory();
    _db = await databaseFactoryIo.openDatabase('${dir.path}/app.db');
    return _db!;
  }

  Future<void> saveUser(int id, Map<String, dynamic> user) async {
    final db = await database;
    await _store.record(id).put(db, user);
  }

  Future<Map<String, Object?>?> getUser(int id) async {
    final db = await database;
    return _store.record(id).get(db);
  }

  Future<void> deleteUser(int id) async {
    final db = await database;
    await _store.record(id).delete(db);
  }
}

When to use: Simple document storage, prototype apps, JSON-like data without complex queries.


3. ObjectBox (NoSQL — Object Database)

One of the fastest local databases for Flutter. Uses object-oriented storage — no SQL, no serialization boilerplate.

yaml
dependencies:
  objectbox: ^2.x.x
  objectbox_flutter_libs: any
dart
import 'package:objectbox/objectbox.dart';

()
class Product {
  ()
  int id = 0;

  String name;
  double price;

  Product({required this.name, required this.price});
}

// Usage
final store = await openStore();
final box = store.box<Product>();

// Insert
box.put(Product(name: 'Flutter Book', price: 499.0));

// Query
final products = box.getAll();

// Find by ID
final product = box.get(1);

// Delete
box.remove(1);

When to use: High-performance requirements, object-oriented storage, no SQL preference.


Comparison: sqflite vs Sembast vs ObjectBox

Featuresqflite (SQL)Sembast (NoSQL)ObjectBox (NoSQL)
QueryFull SQLSimple filtersObject queries
PerformanceGoodModerateVery High
SchemaFixed (migrations needed)FlexibleFlexible with annotations
RelationshipsNative (JOINs)ManualRelations API
Learning CurveMedium (SQL knowledge)LowLow-Medium
Best ForComplex relational dataSimple JSON dataHigh-speed object storage
EncryptionWith SQLCipher✅ (Pro)

Choosing the Right Local Database

Use CaseRecommended
Simple app config / preferences
text
Shared Preferences
Lightweight flexible storage
text
Hive
or
text
Sembast
Structured relational data
text
sqflite
or
text
Drift
High-performance object storage
text
ObjectBox
or
text
Isar
Type-safe SQL with migrations
text
Drift

Tip: For most Flutter apps, sqflite (SQL) or Hive (NoSQL) covers the majority of use cases. Use ObjectBox or Isar when performance is critical (e.g., large datasets, frequent queries).