tezvyn:

Hive: A Fast, Local Key-Value Store for Dart

AI-drafted, machine-checkedSource: pub.devintermediate

Hive is a lightweight key-value database for Dart, acting like a persistent, super-fast Map. Use it to store simple data like user settings or cache API responses locally.

WHY IT EXISTS Hive was created to provide a simple, high-performance, pure-Dart local storage solution for Flutter and Dart apps. It fills the gap between basic key-value stores like SharedPreferences and full-fledged databases like SQLite, offering speed and object storage without native dependencies.

THE MENTAL MODEL Think of Hive as a persistent Dart Map that lives on the device. You open a "box" (which is like a map instance) and then use familiar put(key, value) and get(key) methods. It's designed to be so fast that you can read from a box directly in a Flutter widget's build method without causing performance issues.

HOW IT WORKS Hive stores data in "boxes". Each box is a key-value store that can hold primitives, lists, maps, and custom Dart objects. To store custom objects, you must generate a TypeAdapter, which tells Hive how to convert the object to and from binary. This is usually done with a code generation package. For Flutter apps, the hive_flutter package provides widgets like ValueListenableBuilder that can listen to a box and automatically rebuild the UI when data changes.

WHEN TO USE IT Use Hive for local, non-relational data storage. It's perfect for storing user settings (like a dark mode toggle), caching API responses to make your app faster and work offline, or saving simple application state that needs to persist between sessions. Its write performance significantly outperforms SharedPreferences and SQLite.

WHEN NOT TO USE IT Avoid Hive when you need complex queries, joins, or relationships between different data objects. It is a key-value store, not a relational database. If you need to filter a large dataset by multiple properties or establish links between objects, a more advanced database like Isar (from the same authors) or SQLite would be a better choice.

ONE CANONICAL EXAMPLE To save a user's dark mode preference, you first open a box: await Hive.openBox('settings');. Then, you can write a value synchronously: Hive.box('settings').put('darkMode', true);. To read it back, you simply use get: bool isDarkMode = Hive.box('settings').get('darkMode', defaultValue: false);. After the initial box opening, the read and write operations are immediate and don't require await.

Read the original → pub.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.