Files
worker/lib/core/database/QUICK_START.md
Phuoc Nguyen 628c81ce13 runable
2025-10-17 17:22:28 +07:00

2.5 KiB

Hive CE Quick Start Guide

1. Initialize in main.dart

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'core/database/hive_initializer.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Initialize Hive
  await HiveInitializer.initialize(verbose: true);

  runApp(const ProviderScope(child: MyApp()));
}

2. Save & Retrieve Data

import 'package:worker/core/database/database.dart';

final dbManager = DatabaseManager();

// Save
await dbManager.save(
  boxName: HiveBoxNames.productBox,
  key: 'product_123',
  value: product,
);

// Get
final product = dbManager.get(
  boxName: HiveBoxNames.productBox,
  key: 'product_123',
);

3. Cache with Expiration

// Save to cache
await dbManager.saveToCache(
  key: HiveKeys.productsCacheKey,
  data: products,
);

// Get from cache
final cached = dbManager.getFromCache<List<Product>>(
  key: HiveKeys.productsCacheKey,
  maxAge: CacheDuration.products, // 6 hours
);

if (cached == null) {
  // Cache expired - fetch fresh data
}

4. Create New Model

import 'package:hive_ce/hive.dart';
import 'package:worker/core/constants/storage_constants.dart';

part 'product_model.g.dart';

@HiveType(typeId: HiveTypeIds.product)
class ProductModel extends HiveObject {
  @HiveField(0)
  final String id;

  @HiveField(1)
  final String name;

  ProductModel({required this.id, required this.name});
}

Then run:

dart run build_runner build --delete-conflicting-outputs

5. Logout (Clear User Data)

await HiveInitializer.logout();

Available Boxes

  • HiveBoxNames.userBox - User profile
  • HiveBoxNames.productBox - Products
  • HiveBoxNames.cartBox - Cart items
  • HiveBoxNames.orderBox - Orders
  • HiveBoxNames.projectBox - Projects
  • HiveBoxNames.loyaltyBox - Loyalty data
  • HiveBoxNames.settingsBox - Settings
  • HiveBoxNames.cacheBox - API cache
  • HiveBoxNames.notificationBox - Notifications

See /lib/core/constants/storage_constants.dart for complete list.

Cache Durations

Pre-configured expiration times:

  • CacheDuration.products - 6 hours
  • CacheDuration.categories - 24 hours
  • CacheDuration.loyaltyPoints - 1 hour
  • CacheDuration.rewards - 12 hours
  • CacheDuration.promotions - 2 hours

Need More Info?

  • Full Documentation: /lib/core/database/README.md
  • Setup Summary: /HIVE_SETUP.md
  • Storage Constants: /lib/core/constants/storage_constants.dart