Register DateTime adapter for Hive

This commit is contained in:
2025-07-10 18:23:17 +03:00
parent 1ceacf88fb
commit 56428e9a66
4 changed files with 79 additions and 1 deletions
+1
View File
@@ -6,5 +6,6 @@ import 'package:hive_ce/hive.dart';
@GenerateAdapters([
AdapterSpec<Color>(),
AdapterSpec<IconData>(),
AdapterSpec<DateTime>(),
])
part 'hive_adapters.g.dart';
+55
View File
@@ -83,3 +83,58 @@ class IconDataAdapter extends TypeAdapter<IconData> {
runtimeType == other.runtimeType &&
typeId == other.typeId;
}
class DateTimeAdapter extends TypeAdapter<DateTime> {
@override
final typeId = 2;
@override
DateTime read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int, dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return DateTime(
(fields[0] as num).toInt(),
fields[1] == null ? 1 : (fields[1] as num).toInt(),
fields[2] == null ? 1 : (fields[2] as num).toInt(),
fields[3] == null ? 0 : (fields[3] as num).toInt(),
fields[4] == null ? 0 : (fields[4] as num).toInt(),
fields[5] == null ? 0 : (fields[5] as num).toInt(),
fields[6] == null ? 0 : (fields[6] as num).toInt(),
fields[7] == null ? 0 : (fields[7] as num).toInt(),
);
}
@override
void write(BinaryWriter writer, DateTime obj) {
writer
..writeByte(8)
..writeByte(0)
..write(obj.year)
..writeByte(1)
..write(obj.month)
..writeByte(2)
..write(obj.day)
..writeByte(3)
..write(obj.hour)
..writeByte(4)
..write(obj.minute)
..writeByte(5)
..write(obj.second)
..writeByte(6)
..write(obj.millisecond)
..writeByte(7)
..write(obj.microsecond);
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is DateTimeAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}
+21 -1
View File
@@ -1,7 +1,7 @@
# Generated by Hive CE
# Manual modifications may be necessary for certain migrations
# Check in to version control
nextTypeId: 2
nextTypeId: 3
types:
Color:
typeId: 0
@@ -23,3 +23,23 @@ types:
index: 3
fontFamilyFallback:
index: 4
DateTime:
typeId: 2
nextIndex: 8
fields:
year:
index: 0
month:
index: 1
day:
index: 2
hour:
index: 3
minute:
index: 4
second:
index: 5
millisecond:
index: 6
microsecond:
index: 7
+2
View File
@@ -18,6 +18,7 @@ extension HiveRegistrar on HiveInterface {
registerAdapter(AppSettingsAdapter());
registerAdapter(CategoryAdapter());
registerAdapter(ColorAdapter());
registerAdapter(DateTimeAdapter());
registerAdapter(GlobalSettingsAdapter());
registerAdapter(IconDataAdapter());
registerAdapter(SmsHandlerSettingsAdapter());
@@ -35,6 +36,7 @@ extension IsolatedHiveRegistrar on IsolatedHiveInterface {
registerAdapter(AppSettingsAdapter());
registerAdapter(CategoryAdapter());
registerAdapter(ColorAdapter());
registerAdapter(DateTimeAdapter());
registerAdapter(GlobalSettingsAdapter());
registerAdapter(IconDataAdapter());
registerAdapter(SmsHandlerSettingsAdapter());