Flutter Advanced Hive Database Usage (2024)

Let’s make a more effective database solution with hive package solution for flutter projects.

Flutter Advanced Hive Database Usage (3)

I’ve used hive a lot and it works well with pretty fast and useful solutions. If you hear about hive solution for the first time, read this documentation and make some examples. So when you decide to use hive, you can use this article. The article will teach you some technical stuff, but you can also implement your own architecture ideas.

There are five layers to this solution:

  • Manager of databases
    - Model
    - Mixin
  • Operation
  • Encryption
  • Type
  • A primitive database manager

And lastly, testing. Writing readable, testable code is my goal.

Flutter Advanced Hive Database Usage (4)

I’ll try to explain these schema this coding section.

Database Manager

We’ll be able to use our core operations through this layer. It’s an abstract class that decides boundaries. The start and delete operations will be handled by this layer. If you want another database, just change the layer or give a paramater about the database.

Read this carefully, because it’s important when using hive. In normal cases, hive creates boxes in the application directory, but I made a subdirectory and started it there. That usage will earn you points in the remove section Hive package supports the clear method by default, but it only works for opened boxes. That’s why this code removes all instances in this path. It’s more safe and complete when you remove, or clean your Hive instance.

Database Operation

Many database solutions have methods like put, remove, get, etc. This layer creates operations for your hive model class. As an example, I created a user model that extends the hive model. The class will be used by the hive operation and will make all the methods required.

mixin HiveModelMixin {
/// Your model need to unique key like id
String get key;
}

On the core side, it’ll make hive logical. The operation class gains a T type for generic use, and this type uses the box name. On the other hand, it will open the box encrypted. Please be careful how the encryption feature is implemented.

You’ll be able to manage your project keys with Encryption class. The encryption key is made for hive, but you have to keep data somewhere else (secure context, shared, etc.). It encrypts your box directly, and your data can’t be read by users. The encryption class works with the Primitive database installation. Later, I’ll think about why I implemented this database instance layer. Of course it’s testable and expandable.

Let’s take a look at user operation. It’s actually pretty easy to use. Just make a class that extends Operation. Storage and business operations will be handled by this class.

/// The class `UserHiveOperation` is a subclass of `HiveDatabaseOperation` specifically designed for performing operations
/// on `User` objects in a Hive database.
class UserHiveOperation extends HiveDatabaseOperation<User> {
UserHiveOperation({required super.primitiveDatabase});
}

Database type

Using your data model with Hive requires some coding. This type class sums up all box indexes. Use this class to see how many database models you have in your project.

@immutable
final class HiveTypes {
const HiveTypes._();

static const int userModelId = 1;
}

Primitive Database

The important thing about Hive is that it can store generic data, but many times I need to store data with a primary key. It just needs to read and write anywhere. This part solves extendable/changeable.

Flutter projects can use secure context for many samples, so I used that. You can change that logic by using keychains or whatever. Secure databases can’t be removed by anyone without your bundle. I’d like to write a test for this part, but I can’t implement secure context for just dart console. It provides a flexible database layer for every class that extends itself.

Before testing, that’s all. Let’s do a test.

My main thought was to test my operation with accuracy. It created read, write, stream, and delete operations. I already talked about primitive databases. It’s time. To keep encrypted keys, I’ll create an instance primitive test database and inject it into this layer.

Firstly, we need to make an implementation code for the user process and the database.

void main() {
final hiveDatabaseManager = HiveDatabaseManager();
final userDatabaseOperation = UserHiveOperation(
primitiveDatabase: PrimitiveDatabaseTest(),
);

/// create dumy user
const user = User(
githubId: 1234,
name: 'test',
photo: 'test',
githubUrl: 'test',
shortBio: 'test',
userName: 'vb10',
);
setUp(
() {
// You should look github repository for detail
PathProviderPlatform.instance = FakePathProviderPlatform();

Hive.init('test/database/vb10/');
hiveDatabaseManager.initialOperation();
},
);
..
}

The architecture work will make this test more unstable. There’s more we can write, but it’s enough for this version.

Thats it we’re ready to use hive deep dive.

In my public project, I used this article. The scene works when the user login in from github. I have inherited widget with this hive manager and it uses whole project directly with inherited widget.

I created a user github manager to manage this. Login creation will keep user data both in context and in cache.

This code works for caching and authorization when user presses avatar button in appbar or welcome screen.

There are a lot of problems that Hive can solve, but you have to add some structural solutions

Be careful implementing any 3.party package, like this one. (like hive clear)

In a project structure, you can only share general methods publicly, otherwise the core methods won’t be able to access other users or projects. (like init, key, etc.)

Thank you for reading.
See you in new articles 🍀

Flutter Advanced Hive Database Usage (2024)
Top Articles
Latest Posts
Article information

Author: Jeremiah Abshire

Last Updated:

Views: 5951

Rating: 4.3 / 5 (74 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Jeremiah Abshire

Birthday: 1993-09-14

Address: Apt. 425 92748 Jannie Centers, Port Nikitaville, VT 82110

Phone: +8096210939894

Job: Lead Healthcare Manager

Hobby: Watching movies, Watching movies, Knapping, LARPing, Coffee roasting, Lacemaking, Gaming

Introduction: My name is Jeremiah Abshire, I am a outstanding, kind, clever, hilarious, curious, hilarious, outstanding person who loves writing and wants to share my knowledge and understanding with you.