Hive Steps - Connect Flutter with Hive.
Hive introduction Ref Hive https://pub.dev/packages/hive
Step-1 Get the dependencies of Hive and Hive Flutter
Include in pubspec.yaml file
Under the dependencies
These dependencies are the part of Bundle (APK) , Web , Desktop
dependencies:
hive: ^2.2.3
hive_flutter: ^1.1.0
Step-2 Add the Generator Dependency
These dependencies are the part of only the development
dev_dependencies:
hive_generator: ^1.1.3
build_runner: ^2.2.0
Step-3 Do the Hive Initialise in main.dart file
// Initialise the Hive
await Hive.initFlutter(); // As we are using await so we need to put the async at main
// Register the Adapter
Hive.registerAdapter(PersonAdapter()); // For Binary Read and Write.
NOTE: Before Register for the Adapter we need to generate the Adapter first. Following are the steps for generating the adapter.
We create the model first add the required annotations and add the part of the adapter (Generate file will be)
import 'package:hive_flutter/hive_flutter.dart';
part 'person.g.dart';
@HiveType(typeId: 0)
class Person {
@HiveField(0)
late String email;
@HiveField(1)
late String password;
Person() {}
Person.takeInput({required this.email, required this.password});
@override
String toString() {
// TODO: implement toString
return "Email " + email + " Password " + password;
}
}
Now we need to generate the adapter using build_runner command.
flutter pub run build_runner serve --delete-conflicting-outputs
Run this command in terminal, under the project folder.
In main.dart I open the box , you can do the same in your screen as well.
Box<Person> box = await Hive.openBox('persons');
Step-4 Suppose in register screen I want to use hive. And in my case I create the box inside the main. So I pass hive box object to the screen.
runApp(MaterialApp(home: Register(box)));
Step-5 In register screen we want to add the data inside the box, and we want to display the data.
To add the data in the box call, but make sure first create the person object and fill the required data
box.add(_person);
To print the data in Screen
We use the ValuableListenableBuilder widget, so we listen the box.listenable
Container(
height: 200,
child: ValueListenableBuilder<Box<Person>>( // this is a widget
valueListenable: widget.box.listenable(), // Box get read.
builder: (context, Box<Person> box, Widget? widget) { // Data comes so build the widget using builder function
if (box.isEmpty) {
return Text('No Data in Box');
} else {
return ListView.builder(
itemCount: box.length,
itemBuilder: (context, int index) {
return Text(box.getAt(index)!.email); // get the one by one box value.
});
}
},
))
That' all Folks, Happy Learning :).