DualStore

DualStore is a lightweight local database engine for Dart and Flutter applications.

It provides typed boxes, model adapters, persistent storage, database events, database state tracking, file management, and database compaction.

Example List

Features

Core Database

  • ๐Ÿ“ฆ Typed Boxes

    • Store and retrieve strongly typed IDuModel objects.
    • Access data through DuBox<T>.
  • ๐Ÿ’พ Persistent Local Storage

    • Store application data in a local database file.
    • Data remains available after the application is restarted.
  • ๐Ÿ”ข Automatic Record IDs

    • Records receive automatically generated IDs.
    • Access the generated ID through generatedId.
  • ๐Ÿ”„ Database Reload

    • Reload the current database from disk.
    • Reload conditionally when the database is not already opened.
  • ๐Ÿ“‚ Change Database Path

    • Change the active database file path.
  • ๐Ÿ”’ Database Lifecycle Management

    • Open, reload, flush, and close the database explicitly.

Model & Adapter System

  • ๐Ÿงฉ Custom Model Adapters

    • Register custom model types with IDuMetaAdapter.
    • Convert Dart models to storage-compatible maps.
    • Restore models from stored data.
  • ๐Ÿท๏ธ Type-based Box Access

    • Retrieve a box using the model type:
final todoBox = store.getBox<Todo>();
  • ๐Ÿ“ Custom Serialization
    • Models can define their own serialization logic.
    • toMap() and fromMap() control how model data is stored.

Reactive Events

  • โšก Database Events

    • Listen for database lifecycle events.
  • ๐Ÿ“ฆ Box Events

    • Listen for changes made to boxes.
  • โŒ Error Events

    • Receive database errors through the event system.
  • ๐Ÿ”„ Flutter Reactive UI

    • Integrates naturally with StreamBuilder and other stream-based UI architectures.

Example:

store.events.box.all.listen((event) {
  print('Box Event: $event');
});

Database State

DualStore exposes database state through store.state.

store.state.lastId
store.state.deletedCount
store.state.deletedSize

Available state information includes:

  • Current/last generated record ID
  • Number of deleted records
  • Storage size occupied by deleted records
  • Current database state

This information can be used to monitor database usage and determine when maintenance is required.

Database Maintenance

  • ๐Ÿงน Database Compaction
    • Reclaim space occupied by deleted records.
    • Reduce unused storage inside the database file.
final result = await store.compact();
  • ๐Ÿ’ฝ Flush to Disk
    • Explicitly flush database contents to disk.
final result = await store.flush();

Result-based API

Database operations return:

Result<T, String>

instead of requiring exceptions for normal operation failures.

For example:

final result = await store.open(path);

if (result.isErr) {
  print(result.unwrapError());
}

This makes database operations easier to handle explicitly.


Database API

Create a Store

final store = DualStore();

Register an Adapter

Register an adapter before accessing its corresponding box.

store.registerAdapter(TodoAdapter());

After registration:

final todoBox = store.getBox<Todo>();

If an adapter has not been registered, getBox<T>() throws an exception indicating that the adapter needs to be registered.


Opening a Database

Open a database at a specific path:

final result = await store.open('/path/to/database.du');

The result contains:

  • Ok(true) when the database is opened
  • Ok(false) when applicable according to the operation
  • Err(String) when an error occurs

You can also check whether the database is currently opened:

if (store.opened) {
  print('Database is open');
}

Get the current database path:

print(store.path);

Open If Not Already Opened

If your application may initialize the database multiple times, use:

final result = await store.openIfNotOpened(path);

If the database is already opened, the operation returns:

Ok(false)

Otherwise it opens the database.


Changing the Database Path

The active database file can be changed:

final result = await store.changePath(
  '/path/to/new_database.du',
);

This is useful when an application needs to switch between database files.


Reloading the Database

Reload the current database:

final result = await store.reload();

Or reload only when the database has not already been opened:

final result = await store.reloadIfNotOpened();

Flushing Data

Flush the database contents to disk:

final result = await store.flush();

This can be used when an application needs to explicitly synchronize the database file with the underlying storage.


Closing the Database

Close the database when it is no longer needed:

final result = await store.close();

In Flutter, it is recommended to close the database when the owning component is disposed:

@override
void dispose() {
  store.close();
  super.dispose();
}

Typed Boxes

A box provides typed access to a specific model.

final DuBox<Todo> todoBox = store.getBox<Todo>();

The type parameter ensures that the box works with the expected model type.

For example:

final todo = Todo(
  title: 'Learn DualStore',
  checked: false,
  date: DateTime.now(),
);

await todoBox.add(todo);

Model Adapter

A model adapter connects a Dart model with DualStore's storage system.

class TodoAdapter extends IDuBinaryMetaAdapter<Todo> {
  @override
  int get adapterId => 1;

  @override
  Todo fromMap(Map<String, dynamic> map) {
    return Todo.fromJson(map);
  }

  @override
  Map<String, dynamic> toMap(Todo value) {
    return value.toJson();
  }
}

The adapter is responsible for converting between:

Dart Model
    โ†•
Map<String, dynamic>
    โ†•
DualStore Storage

Events

DualStore provides an event system for observing database activity.

Error Events

store.events.error.all.listen((event) {
  print('[DualStore Error]: $event');
});

Box Events

store.events.box.all.listen((event) {
  print('Box Event: $event');
});

Database Open Events

store.events.open.listen((event) {
  print('Database opened');
});

These events can be used to keep a Flutter UI synchronized with database changes.


Database State

The database state is available through:

final state = store.state;

For example:

print(state.lastId);
print(state.deletedCount);
print(state.deletedSize);

lastId

The latest generated record ID.

deletedCount

The number of records that have been deleted.

deletedSize

The amount of storage currently associated with deleted records.

These values can be used to implement database maintenance logic.


Database Compaction

When records are deleted, their storage may remain available for future database maintenance.

DualStore provides:

final result = await store.compact();

A simple maintenance check can be implemented as:

if (store.state.deletedCount > 0) {
  final result = await store.compact();

  if (result.isErr) {
    print(result.unwrapError());
  }
}

This makes it possible for an application to decide when database compaction should be performed.


image box example

  final ad = st.getImageFileAdapter;
  final imgBox = st.getImageBox;

  await imgBox.add(
    .fromFile(
      File(
        '/home/thancoder/Pictures/ChatGPT Image Sep 19, 2026, 02_12_12 PM.png',
      ),
    ),
  );
  await imgBox.deleteById(1);

  for (var f in await imgBox.getAll()) {
    print(f);
    print('id: ${f.generatedId}');
    final d = await f.imageData;
    if (d.isOk) {
      print('data: ${d.unwrap().length}');
    }
    if (d.isErr) {
      print('image error: ${d.unwrapError()}');
    }
  }

Custom Adapter

class User extends IDuModel {
  final String name;
  final int age;
  final List<String> tags;
  User({required this.name, required this.age, required this.tags});

  @override
  String toString() => '''User(name: $name, age: $age, tags: $tags)''';

  Map<String, dynamic> toJson() {
    return {'name': name, 'age': age, 'tags': tags};
  }

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      name: json['name'],
      age: json['age'],
      tags: List<String>.from(json['tags']),
    );
  }
}

class UserAdapter extends IDuBinaryMetaAdapter<User> {
  @override
  int get adapterId => 1;

  @override
  User fromMap(Map<String, dynamic> map) {
    return User.fromJson(map);
  }

  @override
  Map<String, dynamic> toMap(User value) {
    return value.toJson();
  }
}

Custom Box

final userBox = store.getBox<User>();
userBox.getAll();
userBox.add([User]);
userBox.update(id, [User]);
userBox.deleteById(id);
userBox.events.all.listen((event) {
  print('user event: $event');
});

Reader Store Header

final res = await DualStore.readHeader('user.du');
// final res = DualStore.readHeaderSync('user.du');


switch (res) {
  case Ok(value: final val):
    print('header: $val');
  case Err(value: final err):
    print('Err: $err');
}

Custom parentId

final emailBox = store.getBox<Email>();
  // use  @override
  // int parentId(Email value) {
  //   return value.userId;
  // }
  emailBox.getAllstream(parentId: ["your user generated id"]).listen((emailList) {
    print('email parent id');
  });


  class UserAdapter extends IDuBinaryMetaAdapter<User> {
  @override
  int get adapterId => 1;

  @override
  User fromMap(Map<String, dynamic> map) {
    return User.fromJson(map);
  }

  @override
  Map<String, dynamic> toMap(User value) {
    return value.toJson();
  }
}

class EmailAdapter extends IDuBinaryMetaAdapter<Email> {
  @override
  int get adapterId => 2;

  @override
  int parentId(Email value) {
    return value.userId; // add -> parentId
  }

  @override
  Email fromMap(Map<String, dynamic> map) {
    return .fromJson(map);
  }

  @override
  Map<String, dynamic> toMap(Email value) {
    return value.toJson();
  }
}

class User extends IDuModel {
  final String name;
  final int age;
  User({required this.name, required this.age});

  @override
  String toString() => '''User(ID: $generatedId, name: $name, age: $age)''';

  Map<String, dynamic> toJson() {
    return {'name': name, 'age': age};
  }

  factory User.fromJson(Map<String, dynamic> json) {
    return User(name: json['name'], age: json['age']);
  }
}

class Email extends IDuModel {
  final int userId;
  final String email;

  Email({required this.userId, required this.email});

  Map<String, dynamic> toJson() {
    return {'userId': userId, 'email': email};
  }

  factory Email.fromJson(Map<String, dynamic> json) {
    return Email(userId: json['userId'], email: json['email']);
  }
}

Result API

Most database operations use:

Result<T, String>

This allows operations to report success or failure explicitly.

Example:

final result = await store.open(path);

if (result.isOk) {
  print('Database opened successfully');
}

if (result.isErr) {
  print('Failed to open database: ${result.unwrapError()}');
}

This avoids relying exclusively on exceptions for expected database operation failures.


Todo Example

A complete Todo example can be built using:

class Todo extends IDuModel {
  final String title;
  final bool checked;
  final DateTime date;

  Todo({
    required this.title,
    required this.checked,
    required this.date,
  });

  Map<String, dynamic> toJson() {
    return {
      'title': title,
      'checked': checked,
      'date': date.millisecondsSinceEpoch,
    };
  }

  factory Todo.fromJson(Map<String, dynamic> json) {
    return Todo(
      title: json['title'],
      checked: json['checked'],
      date: DateTime.fromMillisecondsSinceEpoch(json['date']),
    );
  }

  Todo copyWith({
    String? title,
    bool? checked,
    DateTime? date,
  }) {
    return Todo(
      title: title ?? this.title,
      checked: checked ?? this.checked,
      date: date ?? this.date,
    );
  }
}

Then register the adapter:

store.registerAdapter(TodoAdapter());

Open the database:

await store.open('/path/to/todo.du');

Get the typed box:

final todoBox = store.getBox<Todo>();

And start working with Todo records:

await todoBox.add(todo);

Typical Architecture

A typical DualStore application can be structured like this:

                    Flutter Application
                           โ”‚
                           โ–ผ
                      DualStore
                           โ”‚
             โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
             โ–ผ                           โ–ผ
        Model Adapters                 Events
             โ”‚                           โ”‚
             โ–ผ                           โ–ผ
        DuBox<T>                    Event Streams
             โ”‚                           โ”‚
             โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                           โ–ผ
                     Dual Engine
                           โ”‚
                           โ–ผ
                     Database File

The application works with typed models and boxes, while the engine handles the underlying database operations.


Feature Overview

Feature Supported
Persistent local database โœ…
Typed DuBox<T> โœ…
Custom model adapters โœ…
Automatic record IDs โœ…
Add records โœ…
Update records โœ…
Delete records โœ…
Database events โœ…
Box events โœ…
Error events โœ…
Database state โœ…
Database reload โœ…
Conditional open โœ…
Change database path โœ…
Flush to disk โœ…
Database close โœ…
Database compaction โœ…
Result<T, String> API โœ…
Flutter StreamBuilder integration โœ…

Design Goals

DualStore is designed around a few simple goals:

  • Keep the database API small and easy to understand.
  • Provide strongly typed access to stored models.
  • Avoid unnecessary dependencies.
  • Make database errors explicit through Result.
  • Provide event streams for reactive applications.
  • Keep database maintenance accessible through a simple API.
  • Work naturally with Dart and Flutter applications.

Example Project

The included Todo example demonstrates the complete workflow:

Create DualStore
       โ”‚
       โ–ผ
Register TodoAdapter
       โ”‚
       โ–ผ
Open Database
       โ”‚
       โ–ผ
Get DuBox<Todo>
       โ”‚
       โ”œโ”€โ”€โ”€โ”€ Add Todo
       โ”‚
       โ”œโ”€โ”€โ”€โ”€ Update Todo
       โ”‚
       โ””โ”€โ”€โ”€โ”€ Delete Todo
       โ”‚
       โ–ผ
Listen to Events
       โ”‚
       โ–ผ
Monitor Database State
       โ”‚
       โ–ผ
Compact Database
       โ”‚
       โ–ผ
Close Database

Screenshot

DualStore Todo Example

A simple Flutter Todo application demonstrating how to use DualStore for local persistent storage.

This example shows how to:

  • Open and close a DualStore database
  • Register a custom model adapter
  • Create a typed DuBox<T>
  • Add, update, and delete records
  • Listen to database and box events
  • Read database state such as lastId, deletedCount, and deletedSize
  • Detect when database compaction is needed
  • Compact the database
  • Use IDuModel with generated record IDs
  • Store custom Dart models using JSON-based adapters

Features

  • Add new Todo items
  • Mark Todo items as completed
  • Delete Todo items
  • Display automatically generated record IDs
  • Display Todo creation dates
  • Monitor database statistics
  • Detect deleted records
  • Compact the database when deleted records exist
  • Reactive UI updates using StreamBuilder

Data Model

The Todo model extends IDuModel.

class Todo extends IDuModel {
  final String title;
  final bool checked;
  final DateTime date;

  Todo({
    required this.title,
    required this.checked,
    required this.date,
  });

  Map<String, dynamic> toJson() {
    return {
      'title': title,
      'checked': checked,
      'date': date.millisecondsSinceEpoch,
    };
  }

  factory Todo.fromJson(Map<String, dynamic> json) {
    return Todo(
      title: json['title'],
      checked: json['checked'],
      date: DateTime.fromMillisecondsSinceEpoch(json['date']),
    );
  }

  Todo copyWith({
    String? title,
    bool? checked,
    DateTime? date,
  }) {
    return Todo(
      title: title ?? this.title,
      checked: checked ?? this.checked,
      date: date ?? this.date,
    );
  }
}

Each Todo contains:

Field Type Description
title String Todo title
checked bool Completion state
date DateTime Creation date
generatedId int Automatically generated by DualStore

Adapter

DualStore uses an adapter to convert the model to and from a storable representation.

class TodoAdapter extends IDuBinaryMetaAdapter<Todo> {
  @override
  int get adapterId => 1;

  @override
  Todo fromMap(Map<String, dynamic> map) {
    return Todo.fromJson(map);
  }

  @override
  Map<String, dynamic> toMap(Todo value) {
    return value.toJson();
  }
}

The adapterId uniquely identifies the model adapter inside the database.

Opening the Database

Create a DualStore instance and open the database:

final store = DualStore();

Future<void> init() async {
  await store.open('[your path]/todo.du');
}

Before using the database, register the model adapter:

store.registerAdapter(TodoAdapter());

await store.open(path);

Accessing a Typed Box

A DuBox<T> provides typed access to stored models.

DuBox<Todo> get todoBox => store.getBox<Todo>();

This allows Todo records to be accessed without manually casting objects.

Adding a Todo

A new Todo can be inserted with add():

final todo = Todo(
  title: 'Learn DualStore',
  checked: false,
  date: DateTime.now(),
);

final result = await todoBox.add(todo);

if (result.isErr) {
  print(result.unwrapError());
}

The generated record ID is available through:

todo.generatedId

Updating a Todo

A Todo can be updated by its generated ID:

await todoBox.update(
  item.generatedId,
  item.copyWith(
    checked: true,
  ),
);

For example, the checkbox in the UI can update the completion state:

onChanged: (value) async {
  await todoBox.update(
    item.generatedId,
    item.copyWith(
      checked: value,
    ),
  );
},

Deleting a Todo

A model can delete itself:

await item.delete();

This removes the record from the database and increases the database's deleted-record statistics.

Alternatively, deletion can be performed through the box:

await todoBox.deleteById(item.generatedId);

Reading All Todos

All records can be loaded using:

final todos = await todoBox.getAll();

The example sorts the records by date:

final list = await todoBox.getAll();

list.sort(
  (a, b) => b.date.compareTo(a.date),
);

Database Events

DualStore provides events that can be used to react to database changes.

Error Events

store.events.error.all.listen((event) {
  print('[Du Error Event]: $event');
});

Box Events

store.events.box.all.listen((event) {
  print('Box Event: $event');

  print('lastId: ${store.state.lastId}');
  print('deletedCount: ${store.state.deletedCount}');
  print('deletedSize: ${store.state.deletedSize}');
});

Open Events

store.events.open.listen((event) {
  checkCompact();
});

These events can be connected to Flutter's reactive widgets using StreamBuilder.

Database State

The example displays three important database statistics:

store.state.lastId
store.state.deletedCount
store.state.deletedSize

lastId

The last generated record ID.

deletedCount

The number of deleted records currently tracked by the database.

deletedSize

The amount of storage occupied by deleted records.

These values are useful for determining when database compaction should be performed.

Database Compaction

Deleting records does not necessarily mean that the database file immediately becomes smaller.

The example detects whether deleted records exist:

void checkCompact() {
  if (store.state.deletedCount > 0) {
    if (!mounted) return;

    setState(() {
      needToCompact = true;
    });
  }
}

When deleted records exist, the UI displays a DB Compact button.

Compaction is performed with:

final result = await store.compact();

if (result.isErr) {
  print(result.unwrapError());
}

After successful compaction, the database can reclaim unused storage.

Closing the Database

Always close the store when the Flutter widget is disposed:

@override
void dispose() {
  store.close();
  super.dispose();
}

This ensures that open resources are properly released.

Complete Initialization Flow

The complete initialization flow is:

@override
void initState() {
  store.registerAdapter(TodoAdapter());

  init();

  super.initState();

  store.events.error.all.listen((event) {
    print('[Du Error Event]: $event');
  });

  store.events.box.all.listen((event) {
    print('Box Event: $event');

    print('lastId: ${store.state.lastId}');
    print('deletedCount: ${store.state.deletedCount}');
    print('deletedSize: ${store.state.deletedSize}');

    checkCompact();
  });

  store.events.open.listen((event) {
    checkCompact();
  });
}

Future<void> init() async {
  await store.open('/home/thancoder/Documents/todo.du');
}

Flutter Reactive UI

Because DualStore exposes streams for database events, the UI can react to changes using Flutter's StreamBuilder.

StreamBuilder(
  stream: todoBox.events.all,
  builder: (context, snapshot) {
    return FutureBuilder(
      future: todoBox.getAll(),
      builder: (context, snapshot) {
        final todos = snapshot.data ?? [];

        return ListView.builder(
          itemCount: todos.length,
          itemBuilder: (context, index) {
            final todo = todos[index];

            return Text(todo.title);
          },
        );
      },
    );
  },
)

This allows the UI to refresh when records are added, updated, or deleted.

Storage Flow

The overall data flow is:

Todo
  โ”‚
  โ–ผ
TodoAdapter
  โ”‚
  โ–ผ
DuBox<Todo>
  โ”‚
  โ–ผ
DualStore
  โ”‚
  โ–ผ
todo.du

When reading data, the process works in reverse:

todo.du
  โ”‚
  โ–ผ
DualStore
  โ”‚
  โ–ผ
DuBox<Todo>
  โ”‚
  โ–ผ
TodoAdapter
  โ”‚
  โ–ผ
Todo

Example UI

The example application provides:

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ Todo                    [DB Compact]โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ LastId: 10                          โ”‚
โ”‚ deletedCount: 2                     โ”‚
โ”‚ deletedSize: 128                    โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ ID: 10   Learn Dart       โ˜‘         โ”‚
โ”‚ Date: 2026-09-27T...        [Delete]โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ ID: 9    Build a Todo App  โ˜        โ”‚
โ”‚ Date: 2026-09-27T...        [Delete]โ”‚
โ”‚                                     โ”‚
โ”‚                              [+]    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Why This Example?

This Todo application is intentionally simple. Its main purpose is to demonstrate the core DualStore workflow rather than building a feature-rich Todo application.

The example covers the most important operations:

Register Adapter
       โ†“
Open Store
       โ†“
Get Typed Box
       โ†“
Add / Update / Delete
       โ†“
Listen to Events
       โ†“
Monitor Database State
       โ†“
Compact Database
       โ†“
Close Store

Dart Example

 final st = DualStore();
  st.registerAdapter(UserAdapter());

  st.events.error.all.listen((event) {
    print('event: $event');
  });

  final openRes = await st.open('user.du');

  if (openRes.isErr) {
    print('open error: ${openRes.unwrapError()}');
    return;
  }
  /// db clean up
  //await st.compact();

  DuBox<User> box = st.getBox<User>();

  ///stream all
  box.getAllstream().listen((list) {
    print('stream list: $list');
  });

  // await box.add(
  //   .new(name: 'two', age: 20, tags: ['one', 'two', 'three']),
  //   contentWriter: TextCompressContentWriter('i am compress text'),
  //   diskFlush: true,
  // );
  // await box.deleteById(1, diskFlush: false);
  // await box.deleteById(2, diskFlush: true);

  final list = await box.getAll();

  for (var user in list) {
    print('ID: ${user.generatedId} - user: $user');
    final con = await box.getContent<String>(user);
    if (con.isErr) {
      print('content Error: ${con.unwrapError()}');
      return;
    }
    print('content: ${con.unwrap()}');
  }
  print('opened: ${st.opened}');
  print('lastId: ${st.state.lastId}');
  print('deletedCount: ${st.state.deletedCount}');
  print('deletedSize: ${st.state.deletedSize}');

  await st.close();

Flutter App Example

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

  @override
  State<TodoApp> createState() => _TodoAppState();
}

class _TodoAppState extends State<TodoApp> {
  @override
  void initState() {
    store.registerAdapter(TodoAdapter());
    super.initState();
    store.events.error.all.listen((event) {
      print('[Du Error Event]: $event');
    });
    store.events.box.all.listen((event) {
      print('Box Event: $event');
      print('lastId: ${store.state.lastId}');
      print('deletedCount: ${store.state.deletedCount}');
      print('deletedSize: ${store.state.deletedSize}');
      checkCompact();
    });
    store.events.open.listen((event) {
      checkCompact();
    });
    store.events.compact.all.listen((event) {
      print('compact event');
      checkCompact();
    });
    init();
  }

  @override
  void dispose() {
    store.close();
    super.dispose();
  }

  final store = DualStore();
  DuBox<Todo> get todoBox => store.getBox<Todo>();
  final path = '/home/thancoder/Documents/todo.du';
  bool needToCompact = false;

  Future<void> init() async {
    await store.open(path);

    // store.events.box.
  }

  void addTodo() async {
    // final ad = store.getAdapterOrNull<Todo>();
    // print(ad?.);
    // return;
    final text = await showPromptAlertDialog(
      context,
      'Untitled',
      confirmText: 'New Todo',
    );
    if (!mounted) return;
    if (text == null) return;

    final todo = Todo(title: text, checked: false, date: .now());
    final res = await todoBox.add(todo);
    if (!mounted) return;
    if (res.isErr) {
      showErrorDialog(context, res.unwrapError());
      return;
    }
  }

  void checkCompact() {
    if (store.state.deletedCount > 0) {
      if (!mounted) return;
      needToCompact = true;
    } else {
      needToCompact = false;
    }
    setState(() {});
  }

  void compact() async {
    final res = await store.compact(
      onCompactProgress: (total, loaded) {
        print('compress: ${((loaded / total) * 100).toStringAsFixed(2)}%');
      },
    );
    if (!mounted) return;

    if (res.isErr) {
      showErrorDialog(context, res.unwrapError());
      return;
    }
    showSuccessDialog(context, 'Compact แ€œแ€ฏแ€•แ€บแ€•แ€ผแ€ฎแ€ธแ€•แ€ซแ€•แ€ผแ€ฎ');
    setState(() {});
  }

  ColorScheme get col => Theme.of(context).colorScheme;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Todo'),
        actions: [
          IconButton(onPressed: init, icon: Icon(Icons.refresh_outlined)),
          if (needToCompact)
            FilledButton(onPressed: compact, child: Text('DB Compact')),
        ],
      ),
      body: CustomScrollView(
        slivers: [
          StreamBuilder(
            stream: todoBox.getSearchBox(searchType: .linear).getAllStream(),
            builder: (context, asyncSnapshot) {
              return SliverToBoxAdapter(
                child: Container(
                  padding: .all(10),
                  decoration: BoxDecoration(
                    color: col.surfaceContainer,
                    borderRadius: .circular(15),
                  ),
                  child: Column(
                    children: [
                      Text(
                        'LastId: ${store.state.lastId}',
                        style: TextStyle(fontSize: 18, fontWeight: .w600),
                      ),
                      Text(
                        'deletedCount: ${store.state.deletedCount}',
                        style: TextStyle(fontSize: 18, fontWeight: .w600),
                      ),
                      Text(
                        'deletedSize: ${store.state.deletedSize}',
                        style: TextStyle(fontSize: 18, fontWeight: .w600),
                      ),
                    ],
                  ),
                ),
              );
            },
          ),
          SliverPadding(padding: .all(10), sliver: _listWidget),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: addTodo,
        child: Icon(Icons.add_outlined),
      ),
    );
  }

  Widget get _listWidget {
    return StreamBuilder(
      stream: todoBox.getSearchBox(searchType: .linear).getAllStream(),
      builder: (context, snapshot) {
        final list = snapshot.data ?? [];
        list.sort((a, b) => b.date.compareTo(a.date));
        return SliverList.separated(
          separatorBuilder: (context, index) => SizedBox(height: 10),
          itemCount: list.length,
          itemBuilder: (context, index) {
            final item = list[index];
            return _listItem(item);
          },
        );
      },
    );
  }

  Container _listItem(Todo item) {
    return Container(
      padding: .symmetric(vertical: 4, horizontal: 6),
      decoration: BoxDecoration(
        color: col.surfaceContainer,
        borderRadius: .circular(14),
        boxShadow: [.new(blurRadius: 8, color: col.primary, spreadRadius: 1)],
      ),
      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: .start,
              spacing: 4,
              children: [
                Row(
                  children: [
                    Text(
                      'ID: ${item.generatedId}',

                      style: TextStyle(fontSize: 20, fontWeight: .w600),
                    ),
                    SizedBox(width: 10),
                    Text(
                      'Title: ${item.title}',

                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: .w600,
                        decoration: item.checked ? .lineThrough : null,
                      ),
                    ),
                    SizedBox(width: 20),
                    Checkbox.adaptive(
                      value: item.checked,
                      onChanged: (value) async {
                        todoBox.updateByid(
                          item.generatedId,
                          value: item.copyWith(checked: value),
                        );
                      },
                    ),
                  ],
                ),
                Text('Date: ${item.date.toIso8601String()}'),
              ],
            ),
          ),
          FilledButton.icon(
            style: FilledButton.styleFrom(
              backgroundColor: col.error,
              foregroundColor: col.onError,
            ),
            onPressed: () async {
              // todoBox.deleteById(item.generatedId);
              final res = await item.delete();
              if (res.isErr) {
                print(res.unwrapError());
              }
            },
            label: Text('Delete'),
            icon: Icon(Icons.delete_forever_outlined),
          ),
        ],
      ),
    );
  }
}


class Todo extends IDuModel {
  final String title;
  final bool checked;
  final DateTime date;

  Todo({required this.title, required this.checked, required this.date});

  Map<String, dynamic> toJson() {
    return {
      'title': title,
      'checked': checked,
      'date': date.millisecondsSinceEpoch,
    };
  }

  factory Todo.fromJson(Map<String, dynamic> json) {
    return Todo(
      title: json['title'],
      checked: json['checked'],
      date: DateTime.fromMillisecondsSinceEpoch(json['date']),
    );
  }

  Todo copyWith({String? title, bool? checked, DateTime? date}) {
    return Todo(
      title: title ?? this.title,
      checked: checked ?? this.checked,
      date: date ?? this.date,
    );
  }
}

class TodoAdapter extends IDuBinaryMetaAdapter<Todo> {
  @override
  int get adapterId => 1;

  @override
  Todo fromMap(Map<String, dynamic> map) {
    return .fromJson(map);
  }

  @override
  Map<String, dynamic> toMap(Todo value) {
    return value.toJson();
  }
}

License

This example is provided as part of the DualStore project.

Libraries

dual_store