2.5 KiB
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 profileHiveBoxNames.productBox- ProductsHiveBoxNames.cartBox- Cart itemsHiveBoxNames.orderBox- OrdersHiveBoxNames.projectBox- ProjectsHiveBoxNames.loyaltyBox- Loyalty dataHiveBoxNames.settingsBox- SettingsHiveBoxNames.cacheBox- API cacheHiveBoxNames.notificationBox- Notifications
See /lib/core/constants/storage_constants.dart for complete list.
Cache Durations
Pre-configured expiration times:
CacheDuration.products- 6 hoursCacheDuration.categories- 24 hoursCacheDuration.loyaltyPoints- 1 hourCacheDuration.rewards- 12 hoursCacheDuration.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