Best Practices for Modeling Data in Hive — Flutter

Bittu Patel
2 min readApr 11, 2021

Hive has no query language and only limited support for sorting, but this is not necessarily a disadvantage. Sorting and filtering is much faster if you do it yourself in Dart.

Introduction

Because key-value stores are very simple, the data can be modeled in a less complicated way than in SQLite. There is no schema, and you can store objects of different types in the same box. But there are a few things you should be aware of.

Key Order

All keys are sorted in lexicographic order by default. You can use this to get a “free” sort. For example, if you want to store users, you could use their last names and unique number as keys to sort them by last name.

You can also provide a custom key sort function. For example, you could sort users in reverse lexicographic order.

Lists vs Auto Increment

If you want to save a list of items, you have two choices. Either you store the list directly as a value (with put(‘myKey’, [1, 2, 3])) or you can store each element individually (with add(1), add(2), etc.).

If you want to store a large list that is updated frequently (for example, a list of messages), you should store the items individually. Otherwise, each time you change an item, the entire list must be written.

Filtering Items

You can easily filter items in your box. For example:

It might be a good idea to cache the result to improve performance.

The End

Congratulations, you have finished this tutorial where you learned how to model data in a hive like a pro.

Do you want to learn more about Hive?

Let us know in the comments below.

www.developerb2.com

--

--

Bittu Patel

Expertise in Frontend, Backend, and Everything in Between