63 lines
1.5 KiB
Dart
63 lines
1.5 KiB
Dart
import 'package:hive_ce/hive.dart';
|
|
|
|
import '../models/user_model.dart';
|
|
|
|
/// Abstract interface for users local data source
|
|
abstract class UsersLocalDataSource {
|
|
/// Get all users from local storage
|
|
Future<List<UserModel>> getUsers();
|
|
|
|
/// Save users to local storage
|
|
Future<void> saveUsers(List<UserModel> users);
|
|
|
|
/// Clear all users from local storage
|
|
Future<void> clearUsers();
|
|
}
|
|
|
|
/// Implementation of UsersLocalDataSource using Hive
|
|
class UsersLocalDataSourceImpl implements UsersLocalDataSource {
|
|
static const String _boxName = 'users';
|
|
|
|
Future<Box<UserModel>> get _box async {
|
|
if (!Hive.isBoxOpen(_boxName)) {
|
|
return await Hive.openBox<UserModel>(_boxName);
|
|
}
|
|
return Hive.box<UserModel>(_boxName);
|
|
}
|
|
|
|
@override
|
|
Future<List<UserModel>> getUsers() async {
|
|
try {
|
|
final box = await _box;
|
|
return box.values.toList();
|
|
} catch (e) {
|
|
throw Exception('Failed to get users from local storage: $e');
|
|
}
|
|
}
|
|
|
|
@override
|
|
Future<void> saveUsers(List<UserModel> users) async {
|
|
try {
|
|
final box = await _box;
|
|
await box.clear();
|
|
|
|
// Save users with their ID as key
|
|
for (final user in users) {
|
|
await box.put(user.id, user);
|
|
}
|
|
} catch (e) {
|
|
throw Exception('Failed to save users to local storage: $e');
|
|
}
|
|
}
|
|
|
|
@override
|
|
Future<void> clearUsers() async {
|
|
try {
|
|
final box = await _box;
|
|
await box.clear();
|
|
} catch (e) {
|
|
throw Exception('Failed to clear users from local storage: $e');
|
|
}
|
|
}
|
|
}
|