What is Hive?
- Flutter course
- Advanced
- Lesson 11/69
- 4 min
Open a fast local NoSQL DB with Hive.
What is Hive?
Hive is a fast local NoSQL database written in pure Dart. It stores data as key-value pairs in containers called box. With no native dependencies, it works on all platforms.
Hive.init('hive_data');
final box = await Hive.openBox('settings');Hive is more capable than shared_preferences but simpler than sqflite.
The box concept
A box is a container that holds key-value pairs; it is similar to a table in SQL but has no fixed structure. Each box has a name and you can open as many as you need. When a box is opened, a file is created on disk and data becomes persistent.
final box = await Hive.openBox('settings');
await box.put('theme', 'dark');Practice Open a box and check it
Initialize Hive with the path 'hive_data'. Open a box named 'test'. Print box.isOpen. Finally close the box.
Starter code
import 'package:hive/hive.dart';
void main() async {
// Hive'ı 'hive_data' yoluyla başlat
// 'test' adında box aç
// isOpen değerini yazdır
// box'ı kapat
}Sample solution
import 'package:hive/hive.dart';
void main() async {
Hive.init('hive_data');
final box = await Hive.openBox('test');
print(box.isOpen);
await box.close();
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What kind of database is Hive?
- In-memory cache only
- Cloud-based service
- Local NoSQL key-value Correct answer
- Remote SQL relational
Explanation: Hive is a local NoSQL database; it stores data as key-value pairs in boxes.
2 Open a box
final box = await Hive.____;
final box = await Hive.openBox('settings');
Explanation: To open a box you use Hive.openBox; the box name is given as a string.
3 Hive parts
| Term | Meaning |
|---|---|
Hive |
NoSQL database |
Box |
Key-value container |
Hive.init |
Initialization |
openBox |
Box opening |