Hivedb Example #
This is an example of using Hivedb to store and query data in a Flutter application.
First, you will need to add the hive and hive_flutter dependencies to your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
hive: ^2.0.4
hive_flutter: ^1.1.0
Then, you can create a Hive database and a box to store your data. For this example, we will create a Task class and a tasks box:
import 'package:hive/hive.dart';
part 'task.g.dart';
@HiveType(typeId: 0)
class Task {
@HiveField(0)
String name;
@HiveField(1)
bool isDone;
Task({required this.name, this.isDone = false});
}
Note that we are using the @HiveType and @HiveField annotations to define the Task class and its fields.
To create the Hive database and box, you can use the following code:
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
Future<void> main() async {
await Hive.initFlutter();
Hive.registerAdapter(TaskAdapter());
await Hive.openBox<Task>('tasks');
}
Here, we are initializing Hive for Flutter, registering the TaskAdapter to serialize and deserialize the Task class, and opening a tasks box to store our tasks.
Now, you can add, retrieve, and delete tasks from the tasks box using the following methods:
import 'package:hive/hive.dart';
Future<void> addTask(String name) async {
final box = Hive.box<Task>('tasks');
await box.add(Task(name: name));
}
List<Task> getTasks() {
final box = Hive.box<Task>('tasks');
return box.values.toList();
}
Future<void> deleteTask(Task task) async {
final box = Hive.box<Task>('tasks');
await box.delete(task.key);
}
Here, we are using the Hive.box method to access the tasks box, and using the add, values, and delete methods to add, retrieve, and delete tasks.
That’s a basic example of using Hivedb to store and query data in Flutter. Of course, you can customize this code to fit your specific use case.