I'm trying to create a try Hive database and facing some issues I can't solve.
my model is
@HiveType(typeId: 1)
class Tasks {
@HiveField(0)
final String task;
@HiveField(1)
final bool isCompleted;
Tasks({required this.task, required this.isCompleted});
}
and the file generated by hive_generator
class TasksAdapter extends TypeAdapter<Tasks> {
@override
final int typeId = 1;
@override
Tasks read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int, dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return Tasks(
task: fields[0] as String,
isCompleted: fields[1] as bool,
);
}
@override
void write(BinaryWriter writer, Tasks obj) {
writer
..writeByte(2)
..writeByte(0)
..write(obj.task)
..writeByte(1)
..write(obj.isCompleted);
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is TasksAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}
in my main()
:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final directory = await getApplicationDocumentsDirectory();
Hive.init(directory.path);
Hive.registerAdapter(TasksAdapter());
await Hive.openBox<Tasks>("TheList");
runApp(const MyApp());
}
I also tried lazy open but the same error is showing in debugging.
my installed dependencies are:
hive: ^2.0.4
hive_flutter: ^1.1.0
path_provider: ^2.0.5
and
build_runner: ^2.1.2
hive_generator: ^1.1.1
The solution is replacing the Hive.init();
with Hive.initFlutter();
from hive_flutter package.
So, the code would be:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final document = await getApplicationDocumentsDirectory();
await Hive.initFlutter(document.path);
Hive.registerAdapter(TodoAdapter());
await Hive.openBox<Todo>('todos');
runApp(const MyApp());
}