DEV Community

Cover image for Power of Flutter Hive DB: No SQL Local Database
Pranil Shah
Pranil Shah

Posted on

Power of Flutter Hive DB: No SQL Local Database

Introduction:

In the ever-evolving world of mobile app development, the need for efficient and reliable local storage solutions is paramount. Enter Flutter Hive DB, a lightweight and fast NoSQL database for Flutter and Dart applications. In this blog post, we'll explore what Flutter Hive DB is, why it stands out among its counterparts, the methods of saving data with Hive, and delve into a detailed example to showcase its prowess.


What is Flutter Hive DB?

Flutter Hive DB is a NoSQL, key-value pair database that is designed specifically for Flutter and Dart applications. Developed by the talented team at Hive, this open-source library is built with simplicity and performance in mind, providing a seamless and efficient way to persistently store and retrieve data locally.

Official Document: Link

Why Hive Stands Out:

1. Lightweight and Fast: Hive is renowned for its lightweight nature and blazing-fast performance. It outshines many other local databases by minimizing overhead and ensuring quick data access, making it an ideal choice for resource-intensive mobile applications.

2. NoSQL Structure: Adopting a NoSQL structure means that Hive is schema-less, allowing for dynamic and flexible data storage. This makes it easy to adapt to changes in your data model without the need for complex migrations.

3. Cross-Platform Compatibility: Flutter Hive DB seamlessly integrates with Flutter and Dart applications, making it a cross-platform solution. Whether you're developing for Android, iOS, or the web, Hive provides a consistent and reliable storage mechanism.

LinkedIn Twitter GitHub Email


Methods of Saving Data with Hive:

Hive supports various methods for saving data, and understanding these methods is crucial for effective data management in your Flutter applications:

1. Box Operations:

put: Adds or updates a key-value pair in the box.
get: Retrieves the value associated with a given key.
delete: Removes a key-value pair from the box.
Enter fullscreen mode Exit fullscreen mode

2. Batch Operations:

putAll: Adds or updates multiple key-value pairs in a single operation.
deleteAll: Removes multiple key-value pairs in a single operation.
Enter fullscreen mode Exit fullscreen mode

3. Custom Adapters: Hive allows developers to create custom adapters for complex data types, enabling the storage of custom objects with ease.


Integration :

Let's walk through the process of integrating Bugfender into a Flutter application:

Adding Dependency:
Add the Bugfender dependency to your pubspec.yaml file:

dependencies:
  hive: ^[version]
  hive_flutter: ^[version]

dev_dependencies:
  hive_generator: ^[version]
  build_runner: ^[version]
Enter fullscreen mode Exit fullscreen mode

2. Initialize :
Initialize Hive with a valid directory in your app files. You can also provide a subdirectory:
await Hive.initFlutter();

Note: Use Hive.init() for non-Flutter apps.

3. Open Box :
All of your data is stored in boxes.

var box = await Hive.openBox('testBox');
Enter fullscreen mode Exit fullscreen mode

You may call box('testBox') to get the singleton instance of an already opened box.

**Note: **Hive supports all primitive types, List, Map, DateTime, BigInt and Uint8List. Any object can be stored using TypeAdapters.

Add Data Basics:
Simply adding data into an already opened box using key-pair.

import 'package:hive/hive.dart';

void main() async {

  var box = await Hive.openBox('testBox');

  box.put('name', 'David');

/// get data from box using key 
  print('Name: ${box.get('name')}');
}
Enter fullscreen mode Exit fullscreen mode

Add Data Using Hive Object :

  • Data Object
@HiveType()
class Person extends HiveObject {
  @HiveField(0)
  String name;
}
Enter fullscreen mode Exit fullscreen mode

Generate adapter using hive_generator

flutter packages pub run build_runner build - delete-conflicting-outputs

Type Adapter :

class PersonAdapter extends TypeAdapter<Person> {
  @override
  final typeId = 0;

  @override
  Person read(BinaryReader reader) {
    return Person()..name = reader.read();
  }

  @override
  void write(BinaryWriter writer, Person obj) {
    writer.write(obj.name);
  }
}
Enter fullscreen mode Exit fullscreen mode

When to Use?

Hive is very performant because it has little overhead compared to relational databases. The API is very close to how the data is stored on the disk.
Key-value databases can be used to store almost any kind of data. For example:

  • User profiles
  • Session information
  • Article/blog comments
  • Messages
  • Shopping cart contents
  • Product categories
  • Binary data
  • etc.

Hive is also one of the best options when it comes to cross-platform support. You don't have to include binaries, and it works in the browser using IndexedDB.
If you use the shared_preferences packages and don't need to access them from native code, you should always use Hive instead.

When not to use Hive

Every kind of data can be stored in Hive when modeled correctly. That being said, it might sometimes be more convenient to use a relational database like SQLite. (More convenient, not faster!)

  • Especially if your data has complex relations and you rely heavily on indices and complex queries, you should consider using SQLite.

  • Since Hive is so lightweight and will hardly increase your app size at all, you can also use Hive and other solutions together.


Export Stored Data of Hive :
Android :

Android Studio > Device File Explorer > data > data > your_package_name > box_name.hive

  1. iOS :
    Xcode > Organiser > your_app > download_container > show package content > box_name.hive

  2. Visualise Data :
    Link: You can drop your .hive file here

Flutter with hive by Pranil Shah

Conclusion:

Flutter Hive DB stands as a testament to the power of simplicity and efficiency in local storage solutions. With its lightweight design, NoSQL structure, and cross-platform compatibility, it has earned its place as a go-to database for Flutter and Dart developers. By understanding the various methods of saving data with Hive and exploring practical examples, you can harness the full potential of this versatile database in your mobile applications.
Let's Connect and follow for more.

LinkedIn Twitter GitHub Email

Top comments (0)