Top Related Projects
Flutter database for super-fast Dart object persistence
Quick Overview
Hive is a lightweight and blazing fast key-value database implemented in pure Dart. It's designed to be easy to use and efficient for mobile and desktop applications, with support for strong encryption and custom objects.
Pros
- Extremely fast performance, outperforming many other mobile databases
- Simple and intuitive API, making it easy to learn and use
- Cross-platform support (iOS, Android, Windows, Mac, Linux)
- Built-in support for encryption and custom objects
Cons
- Limited query capabilities compared to full-fledged SQL databases
- Not suitable for complex relational data structures
- Lack of built-in support for remote synchronization
- Relatively new project, which may lead to potential stability issues or API changes
Code Examples
- Opening a box and storing data:
var box = await Hive.openBox('myBox');
box.put('name', 'John');
box.put('age', 30);
- Reading data from a box:
var name = box.get('name');
var age = box.get('age');
print('Name: $name, Age: $age');
- Working with custom objects:
@HiveType(typeId: 0)
class Person extends HiveObject {
@HiveField(0)
String name;
@HiveField(1)
int age;
Person(this.name, this.age);
}
// Register the adapter
Hive.registerAdapter(PersonAdapter());
// Store a custom object
var person = Person('Alice', 25);
box.add(person);
- Using transactions for batch operations:
await box.transaction((txn) async {
txn.put('key1', 'value1');
txn.put('key2', 'value2');
txn.delete('key3');
});
Getting Started
To start using Hive in your Dart project:
-
Add Hive to your
pubspec.yaml
:dependencies: hive: ^2.2.3 hive_flutter: ^1.1.0
-
Initialize Hive in your main function:
import 'package:hive_flutter/hive_flutter.dart'; void main() async { await Hive.initFlutter(); runApp(MyApp()); }
-
Open a box and start using Hive:
var box = await Hive.openBox('myBox'); box.put('key', 'value'); var value = box.get('key');
Competitor Comparisons
Flutter database for super-fast Dart object persistence
Pros of ObjectBox
- Better performance for complex queries and large datasets
- Supports relations between objects, allowing for more sophisticated data modeling
- Offers automatic schema migration, simplifying database updates
Cons of ObjectBox
- Steeper learning curve due to more complex API
- Requires native libraries, which can complicate cross-platform development
- Less community support and fewer resources compared to Hive
Code Comparison
ObjectBox:
@Entity()
class Person {
int id;
String name;
int age;
Person({this.id = 0, required this.name, required this.age});
}
final box = store.box<Person>();
box.put(Person(name: "John", age: 30));
Hive:
@HiveType(typeId: 0)
class Person extends HiveObject {
@HiveField(0)
String name;
@HiveField(1)
int age;
Person({required this.name, required this.age});
}
final box = Hive.box<Person>('persons');
box.add(Person(name: "John", age: 30));
Both ObjectBox and Hive are popular local database solutions for Dart and Flutter. ObjectBox offers better performance for complex scenarios and supports relations, but has a steeper learning curve. Hive is simpler to use and more lightweight, making it ideal for smaller projects or those new to local databases in Flutter.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Fast, Enjoyable & Secure NoSQL Database
Hive is a lightweight and buzzing-fast key-value database made for Flutter and Dart.
Features ð
- ð Bee everywhere: mobile, desktop, browser
- ð Buzzing speed: Faster than a bee on caffeine!
- ð¡ Sweet, powerful, & intuitive API
- ð Queen's Guard: Encryption built right in.
- ð§ Thinking in swarms: Multi-isolate support.
- ð¯ Everything a bee needs and more!
Bee fact: A single bee can visit 5,000 flowers in a day!
Buzz into Action ð
Feeling the excitement? Great! Let's help you take your first flight with Hive.
ð Add dependencies
To kickstart the journey add hive
, isar_flutter_libs
and path_provider
to your pubspec.yaml
.
dependencies:
hive: ^4.0.0
isar_flutter_libs: ^4.0.0-dev.13
path_provider: ^2.1.0
Pssst! 𤫠path_provider
will help you to find the optimal directory for each platform.
ð¡ Designate a Home
Hive needs a place to call home. Using path_provider
we can find a valid directory.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final dir = await getApplicationDocumentsDirectory();
Hive.defaultDirectory = dir.path;
// ...
}
ð And... Action!
Woohoo! You're all set. Jump in and let your Hive adventure begin!
import 'package:hive/hive.dart';
final box = Hive.box();
box.put('name', 'David');
final name = box.get('name');
print('Name: $name');
Bee fact: Honeybees can fly at a speed of up to 30 kilometers per hour!
ð Hive Handbook
In Hive, data is neatly organized into containers known as boxes. Think of boxes as tables you'd find in SQL, but far more flexible â they don't stick to a set structure and can contain a variety of data. Boxes can be encrypted to store sensitive data.
Table of Contents
Want to jump to a specific section? Here's a handy table of contents:
- Opening Boxes
- Closing Boxes
- Inserting
- Reading
- Deleting
- Using Boxes like Lists
- Type safety
- Non-primitive Objects
- Transactions
- Isolates
- FAQ
Bee fact: Bees have five eyes â three simple eyes on top of the head, and two compound eyes, with numerous hexagonal facets.
ð¦ Opening Boxes
Your journey with Hive begins with opening your first box. Trust me, it's unbee-lievably easy:
final box = Hive.box(name: 'myBox');
When you call Hive.box(name: 'myBox')
for the first time with a given name, Hive will create a new box for you. If you call it again with the same name, Hive will return the already existing box.
You can also use Hive.box()
without providing a name. In this case, Hive will return the default box.
There are optional parameters you can pass to Hive.box()
:
Parameter | Description |
---|---|
name | Label your box with a distinct name |
directory | Select a home for your box. If omitted, Hive uses the defaultDirectory . |
encryptionKey | Hand over this key, and Hive will encrypt your box. Keep it safe! |
maxSizeMiB | The maximum size of the box in MiB. Go for a modest number. |
Bee fact: Beeswax, which is secreted from the abdomen of worker bees, is used to construct the honeycomb.
ð Bidding Adieu: Closing Boxes
It's not advised to close boxes that might be accessed again. This prevents unnecessary overhead of reopening the box and ensures smooth data retrieval.
To close a box just call box.close()
. Wipe the box from the face of the earth with box.deleteFromDisk()
.
Bee fact: When a bee finds a good source of nectar, it flies back to the hive and shows its friends where the nectar source is by doing a dance.
âï¸ Filling the Honeycomb: Inserting Data
Once we have a box, it's time to fill it with sweet data! At its core, a box is just a key-value store. String keys are mapped to arbitrary primitive values. You can think of a box as a persisted Map<String, dynamic>
.
final box = Hive.box();
box.put('danceMoves', 'Waggle Dance');
box.put('wingSpeed', 200);
Updating values? If a particular key already exists, Hive simply updates its corresponding value. And complex types like lists and maps? They're in too!
box.put('friends', ['Buzzy', 'Stinger', 'Honey']);
box.put('memories', {'firstFlight': 'Sunny Day', 'bestNectar': 'Rose'});
Instead of .put()
you prefer the syntax of maps? Hive gets you:
box['danceMoves'] = 'Round Dance';
box['wingSpeed'] = 220;
Got a bucket of honey facts? Drop them all at once with box.putAll()
:
box.putAll({'favoriteFlower': 'Lavender', 'wingSpeed': 210});
Bee fact: A single bee colony can produce anywhere from 30 to 100 pounds of honey in a year, depending on the availability of nectar sources.
ð Extracting Honey... I mean, Data!
Need a snippet of info from your Hive? No need to don the beekeeper suit; just scoop it out using box.get()
or box.getAll()
. If a key doesn't exist, box.get()
simply return a null
. But fret not; you can tell it to have a backup plan:
final box = Hive.box(name: 'beeees');
final fav = box.get('favoriteFlower');
final moves = box.get('danceMoves', defaultValue: 'waggle');
Oh, and if you're feeling fancy, use the []
operator for a more stylish approach:
final fav = box['favoriteFlower'];
final moves = box['danceMoves'] ?? 'waggle';
Bee fact: Worker bees are the only bees most people ever see flying around outside the hive. They're female, and their roles are to forage for food, build and protect the hive, and more.
𧹠Deleting Data
Time for some spring cleaning in the hive! To remove a single entry from your box, use box.delete()
:
final deleted = box.delete('lavenderHoney');
print('Honey eaten: $deleted'); // Honey eaten: true
Perhaps it's time for a complete reset, making space for a fresh batch of honey. If you're looking to remove all key-value pairs from a box, use box.clear()
:
box.clear();
Bee fact: Bees have been around for more than 30 million years! Their long history predates the existence of humans and even dinosaurs.
⨠Using Boxes like Lists
In the bee world, honeycombs aren't just random compartments; they're methodically organized. Similarly, while we've been viewing Hive boxes as maps so far, they can be used just like lists:
final box = Hive.box();
box.add('Rose');
box.add('Tulip');
print(box.getAt(0)); // Rose
print(box.getAt(1)); // Tulip
But remember, bees can't retrieve honey from a comb that's empty or doesn't exist. Likewise, index-based operations will throw an error if you try an index out of bounds:
final box = Hive.box();
box.add('Daisy');
print(box.getAt(1)); // Error! This will make the bees buzz in confusion
Even if we insert a key-value pair we can still access the values by index.
final box = Hive.box();
box.add('Lily');
box.put('key', 'Orchid');
print(box.getAt(0)); // Lily
print(box.getAt(1)); // Orchid
Of course, we can also use the []
operator in combination with indexes :
final box = Hive.box();
box.add('Marigold');
print(box[0]); // Marigold
box[0] = 'Daffodil';
box[1] = 'Bluebell'; // Error! This will get the bees in a whirl
Bee fact: To produce one pound of honey, a hive's bees must visit 2 million flowers and fly over 55,000 miles.
ð¡ï¸ Type safety
Safety is the bee's priority! To keep your data sweet and pure boxes have an optional generic type parameter. It allows you to store only values of a specific type in a box:
final box = Hive.box<String>(name: 'BeeTreasures');
box.put('DaisyDance', 'SweetNectarShake');
box.put('RoseRumba', 'GoldenPollenParty');
box.put('TulipTango', 777); // Error - You can't fool the bees!
Make sure to use the same type whenever you get the box. Otherwise, you'll get an error:
Hive.box<int>(name: 'BeeTreasures'); // Error - We already have a String box!
Bee fact: Bees have two stomachs. One is for eating, and the other is for storing nectar collected from flowers or water so they can carry it back to their hive. Talk about a sweet backpack!
𧩠Bee-yond the Basics: Non-primitive Objects
Hive goes beyond storing just basic data types! Along with primitives, lists, and maps, Hive can store any Dart object of your liking. The only buzz you need to know? Your object should come equipped with a .fromJson()
and .toJson()
method:
class Bee {
Bee({required this.name, required this.role});
factory Bee.fromJson(Map<String, dynamic> json) => Bee(
name: json['name'] as String,
role: json['role'] as String,
);
final String name;
final String role;
Map<String, dynamic> toJson() => {
'name': name,
'role': role,
};
}
Before our bee-friends can buzz around in Hive, you need to do the beekeeper's job and register the Bee
class:
Hive.registerAdapter('Bee', Bee.fromJson);
Now, you're all set to let your bees fly:
final box = Hive.box();
final bumble = Bee(name: 'Bumble', role: 'Worker');
box.put('BumbleID', bumble);
print(box.get('BumbleID')); // Bumble - Worker
Bee fact: Bees are responsible for pollinating about one-third of the world's food crops.
𪢠Transactions
Transactions are an efficient way to update multiple values at once. They are also useful if you want to make sure that a Box is not changed by other code while you are working with it.
final box = Hive.box();
box.write(() {
box.store('nectar1', 'GoldenNectar');
box.store('nectar2', 'WildflowerBrew');
box.store('nectar3', 'CloverDew');
});
box.read(() {
box.get('nectar1'); // GoldenNectar
});
Changes made in a transaction are always atomic. Either all changes are applied or none of them. So if an error occurs during a transaction, the box will not be changed.
final box = Hive.box();
box.put('honeyLevel', 5);
box.write(() {
box.put('honeyLevel', 6);
throw Exception('Oh no!!!');
});
print(box.get('honeyLevel')); // 5
Bee fact: Bees can recognize human faces, and they can even be trained to associate a picture of a face with sweet treats!
ð The Isolate Dance
Just like a beehive where multiple bees work simultaneously, you can buzz into Hive from various Isolates at the same time. This nifty trick is great when you wish to keep those database activities separate from your UI thread.
Hive comes with a sweet Hive.compute()
method that runs a function in a different isolate. The best part? It also does the honey-making job of setting up and tidying resources for you.
// Opening the bee's box
final box = Hive.box();
// Storing some sweet nectar
box.put('nectarType', 'wildflower');
await Hive.compute(() {
// Accessing the same box from another worker bee
final box = Hive.box();
print(box.get('nectarType')); // wildflower
// Updating the nectar's quality
box.put('nectarType', 'lavender');
});
// Tasting the updated honey flavor
print(honeycomb.get('nectarType')); // lavender
Just remember, while the bees dance in harmony, ensure your Isolates do too! ðð¶
Bee fact: Bees have two pairs of wings, and they beat 11,400 times per minute.
ð¯ Buzzworthy Questions
ð To bee or not to bee: Hive or Isar?
It's not always black and yellow! ð¤ð Both Hive and Isar have their sweet spots. Hive is a lightweight wrapper around Isar so if you are looking for a simple key-value store, Hive might be enough. Isar is the way to go if you need queries, relations, and more advanced features.
ð Will using Hive make my app as fast as a bee?
While we can't promise your app will gain wings, ð¦ Hive sure will give it the speed it deserves. Hive is very resource efficient and optimized for mobile devices. Flutter like a butterfly, sting like a bee! ð
ð Where in the beehive does Hive hide my honey... I mean, data?
Remember the
defaultDirectory
we set at the beginning? ð That's where Hive stores your data in a file namedyourBoxName.isar
oryourBoxName.sqlite
.
ð¸ I've got some bee-autiful images! Can I store them directly in Hive?
While you might be tempted to put those pics right into Hive, ð¼ï¸ it's best to store your images and other binary data as files outside Hive. You can then store the file path in Hive. Think of it like leaving honey out in the open; it's better to keep it neatly stored in the appropriate place. ðº
ð² Yikes! What if my app meets an untimely demise (gets killed)? What becomes of my Hive?
No need for a bee-mergency! ð¨ If your app buzzes off unexpectedly, Hive ensures that your data remains safe and sound. Transactions are atomic, so either all changes are applied or none of them. If an error occurs during a transaction, the box will not be changed.
ð How does Hive keep our data safe from sticky fingers?
We've got the queen's guard on duty! ð¡ï¸ If you encrypt your box Hive uses 256-bit AES in CBC mode. Every database page is safeguarded separately, ensuring your sweet stuff remains secure and only accessible to those with the right key. Buzz-worthy protection, right? ðï¸
ð¤ When should I rally the troops and use transactions?
Just like a hive making big decisions together, ð you'll want to use transactions when you have several operations that should be executed together. If one fails, they all fail. It ensures your data stays consistent, safe, and buzzing in harmony! ð¶
𤣠What if I'm allergic to bees?
No worries! Hive is 100% sting-free, ð« although we're pretty sure you'll get a buzz out of its performance.
â³ Hive operations are synchronous. Doesn't that make the bee waltz a bit slow?
Hive is incredibly fast and efficient. ð It's built on top of Isar, a high-performance database engine. If you want to keep database operations away from your UI isolate, you can use
compute()
orIsolate.run()
to run them in a separate isolate.
ð¦ How many boxes should a wise beekeeper have?
While the sky's the limit in the world of bees, ð in Hive, every box becomes a separate file. So, even if you're buzzing with excitement, it's wise not to overdo it. ð
ð License
Copyright 2023 Simon Choi
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Top Related Projects
Flutter database for super-fast Dart object persistence
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot