Hive CRUD - KindaCode
Introduction to Hive: This repo will teach you how to use hive package for storing data locally in your device. Hive is a lightweight and blazing fast key-value database written in pure Dart.
To use hive, add the following packages to your pubspec.yaml file:
dependencies:
# For NoSQL Database
hive: ^2.2.3
# Extension for hive
hive_flutter: ^1.1.0
dev_dependencies:
# For hive
hive_generator: ^1.1.3
build_runner: ^2.2.0
Create: home_page.dart
List<Map<String, dynamic>> _items = [];
final _shoppingBox = Hive.box('shopping_box');
// Create new item
Future<void> _createItem(Map<String, dynamic> newItem) async {
await _shoppingBox.add(newItem);
_refreshItems(); // update the UI
}
Read: home_page.dart
// Get all items from the database
void _refreshItems() {
final data = _shoppingBox.keys.map((key) {
final value = _shoppingBox.get(key);
return {"key": key, "name": value["name"], "quantity": value['quantity']};
}).toList();
setState(() {
_items = data.reversed.toList();
// we use "reversed" to sort items in order from the latest to the oldest
});
}
// Retrieve a single item from the database by using its key
// Our app won't use this function but I put it here for your reference
// ignore: unused_element
Map<String, dynamic> _readItem(int key) {
final item = _shoppingBox.get(key);
return item;
}
Update: home_page.dart
// Update a single item
Future<void> _updateItem(int itemKey, Map<String, dynamic> item) async {
await _shoppingBox.put(itemKey, item);
_refreshItems(); // Update the UI
}
Delete: home_page.dart
// Delete a single item
Future<void> _deleteItem(int itemKey) async {
await _shoppingBox.delete(itemKey);
_refreshItems(); // update the UI
// Display a snackbar
// ignore: use_build_context_synchronously
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('An item has been deleted')));
}
lib
├── views
│ └── home_page.dart
└── main.dart