flutter_objectbox_provider 1.0.0 copy "flutter_objectbox_provider: ^1.0.0" to clipboard
flutter_objectbox_provider: ^1.0.0 copied to clipboard

A robust ObjectBox database management layer for Flutter applications with alternative keys, HNSW vector search, offline sync capabilities, and transaction management.

example/example.dart

// ignore_for_file: avoid_print

import 'package:flutter_models_provider/global/environment.dart';
import 'package:flutter_models_provider/model/objectbox/coleccion_objectbox_model.dart';
import 'package:flutter_objectbox_provider/flutter_objectbox_provider.dart';
import 'package:flutter_objectbox_provider/objectbox_provider_entities.dart';

/// Example demonstrating basic usage of flutter_objectbox_provider
void main() async {
  // 1. Initialize the ObjectBox provider
  final objectBox = FlutterObjectBoxProvider();

  await objectBox.initStore(
    storeInMemory: false, // Set to true for testing
    maxDBSizeInKB: 1024 * 1024, // 1GB max size
  );

  // 2. Save records
  await saveRecordsExample(objectBox);

  // 3. Read records
  await readRecordsExample(objectBox);

  // 4. Query with filters
  await queryWithFiltersExample(objectBox);

  // 5. Alternative key search
  await alternativeKeyExample(objectBox);

  // 6. HNSW vector search (geolocation example)
  await hnswSearchExample(objectBox);

  // 7. Offline sync example
  await offlineSyncExample(objectBox);

  // 8. Close the store when done
  objectBox.closeStore();
}

/// Example: Save records to ObjectBox
Future<void> saveRecordsExample(FlutterObjectBoxProvider objectBox) async {
  final records = [
    ColeccionObjBox(
      id: 0, // ObjectBox assigns ID automatically
      coleccion: 'users',
      idServer: '',
      idMobile: '',
      data: '{"name": "John", "email": "john@example.com", "city": "Madrid"}',
      dataOriginal:
          '{"name": "John", "email": "john@example.com", "city": "Madrid"}',
      estado: 'A', // A = Active
      creadoEl: DateTime.now().millisecondsSinceEpoch.toString(),
      idAuth: 'auth123',
      coleccionAuth: 'authUsers',
    ),
  ];

  final result = await objectBox.guardarEnObjectBox<ColeccionObjBox>(
    data: records,
    queryPropertiesWrapper: ColeccionObjBoxWrapper(),
    keysAlternative: ['name', 'email', 'city'], // Extract these as alt keys
  );

  if (result.containsKey(EnvironmentApiRest.dataOk)) {
    print('Records saved successfully');
    final savedRecords = result[EnvironmentApiRest.data] as List;
    print('Saved ${savedRecords.length} records');
  } else {
    print('Error: ${result[EnvironmentApiRest.error]}');
  }
}

/// Example: Read a record by ID
Future<void> readRecordsExample(FlutterObjectBoxProvider objectBox) async {
  final result = await objectBox.leerByIdObjectBox<ColeccionObjBox>(
    coleccion: 'users',
    id: 'mobile_123', // or server ID
    tipoId: 'idMobile', // 'idServer' or 'idMobile'
    queryPropertiesWrapper: ColeccionObjBoxWrapper(),
  );

  if (result.containsKey(EnvironmentApiRest.dataOk)) {
    final record = result[EnvironmentApiRest.data] as ColeccionObjBox;
    print('Found record: ${record.data}');
  } else {
    print('Record not found');
  }
}

/// Example: Query records with filters
Future<void> queryWithFiltersExample(FlutterObjectBoxProvider objectBox) async {
  final result = await objectBox.obtenerObjectBox<ColeccionObjBox>(
    coleccion: 'users',
    indexNames: ['estado', 'alternativeKey2'], // Fields to filter
    operador: ['=', '='], // Operators
    values: ['A', 'Madrid'], // Values to match
    queryPropertiesWrapper: ColeccionObjBoxWrapper(),
    ordenar: 'creadoEl', // Sort by creation date
    limit: '10', // Max 10 results
    skip: '0', // Skip 0 records (pagination)
    union: ['AND'], // Combine conditions with AND
  );

  if (result.containsKey(EnvironmentApiRest.dataOk)) {
    final records = result[EnvironmentApiRest.data] as List;
    final totalItems = result['totalItems'] as int;
    print('Found $totalItems records matching filters');
    for (final record in records) {
      print('- ${(record as ColeccionObjBox).data}');
    }
  }
}

/// Example: Search by alternative key
Future<void> alternativeKeyExample(FlutterObjectBoxProvider objectBox) async {
  // Alternative keys are extracted from JSON data during save
  // alternativeKey = name, alternativeKey1 = email, alternativeKey2 = city

  final result = await objectBox.leerByAlternativeKeyObjectBox<ColeccionObjBox>(
    coleccion: 'users',
    alternativeKeyToRead: AlternativeKeyToRead.alternativeKey2, // city field
    valueAlternativeKey: 'Madrid',
    queryPropertiesWrapper: ColeccionObjBoxWrapper(),
    limit: '10',
  );

  if (result.containsKey(EnvironmentApiRest.dataOk)) {
    final records = result[EnvironmentApiRest.data] as List;
    print('Found ${records.length} users in Madrid');
  }
}

/// Example: HNSW vector search for geolocation
Future<void> hnswSearchExample(FlutterObjectBoxProvider objectBox) async {
  // First, save records with HNSW keys (coordinates)
  final locations = [
    ColeccionObjBox(
      id: 0,
      coleccion: 'locations',
      idServer: '',
      idMobile: '',
      data: '{"name": "Barcelona", "country": "Spain"}',
      estado: 'A',
      creadoEl: DateTime.now().millisecondsSinceEpoch.toString(),
      alternativeHnswKey: [41.3851, 2.1734], // Barcelona coordinates
    ),
  ];

  await objectBox.guardarEnObjectBox<ColeccionObjBox>(
    data: locations,
    queryPropertiesWrapper: ColeccionObjBoxWrapper(),
  );

  // Search for nearest locations to Madrid
  final madridCoords = [40.4168, -3.7038];

  final result =
      await objectBox.leerByAlternativeHNSWKeyObjectBox<ColeccionObjBox>(
    coleccion: 'locations',
    alternativeHnswKeyToRead: AlternativeHNSWKeyToRead.alternativeHnswKey,
    queryVector: madridCoords,
    queryPropertiesWrapper: ColeccionObjBoxWrapper(),
    maxResultCount: 5,
  );

  if (result.containsKey(EnvironmentApiRest.dataOk)) {
    final results = result[EnvironmentApiRest.data] as List<Map>;
    for (final item in results) {
      final location = item['item'] as ColeccionObjBox;
      final score = item['score'] as double;
      print('Location: ${location.data}, Distance score: $score');
    }
  }
}

/// Example: Offline sync workflow
Future<void> offlineSyncExample(FlutterObjectBoxProvider objectBox) async {
  // 1. Get records pending transfer (eTransfer == 'D')
  final pendingResult =
      await objectBox.leerPendientesTransferirObjectBox<ColeccionObjBox>(
    coleccion: 'users',
    queryPropertiesWrapper: ColeccionObjBoxWrapper(),
    limit: '100',
  );

  if (pendingResult.containsKey(EnvironmentApiRest.dataOk)) {
    final pendingRecords = pendingResult[EnvironmentApiRest.data] as List;
    print('${pendingRecords.length} records pending sync');

    // 2. After successful server sync, mark as transferred
    final idsToMark = <String>[];
    for (final record in pendingRecords) {
      final colRecord = record as ColeccionObjBox;
      if (colRecord.idMobile.isNotEmpty) {
        idsToMark.add(colRecord.idMobile);
      }
    }

    if (idsToMark.isNotEmpty) {
      await objectBox.actualizoComoTransferidoObjectBox<ColeccionObjBox>(
        coleccion: 'users',
        idsToAct: idsToMark,
        queryPropertiesWrapper: ColeccionObjBoxWrapper(),
      );
      print('Marked ${idsToMark.length} records as transferred');
    }
  }
}
0
likes
130
points
72
downloads

Publisher

unverified uploader

Weekly Downloads

A robust ObjectBox database management layer for Flutter applications with alternative keys, HNSW vector search, offline sync capabilities, and transaction management.

Repository (GitHub)
View/report issues

Topics

#database #objectbox #offline-first #vector-search #persistence

Documentation

API reference

License

MIT (license)

Dependencies

flat_buffers, flutter, flutter_models_provider, flutter_utils_providers, objectbox, objectbox_flutter_libs, path, path_provider, uuid

More

Packages that depend on flutter_objectbox_provider