Persisting data using HiveDB

- Andrés Cruz

En español

HiveDB, along with the sharedpreferences that we saw in a previous post, is one of the popular ways we persist data in our application in Flutter; HiveDB has a simple API to store and obtain data as we will see in this post.

Install and configure HiveDB

Let's start by adding the dependency in our file:

pubspec.yaml

dependencies: 
    hive:
    hive_flutter:

Now, we need to initialize it, for that, we add the following line of code in the main.dart:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();
  runApp(ProviderScope(child: MyApp()));
}

It is the more or less typical code that we use when initializing asynchronous processes at the level of the entire application and with Hive.initFlutter() we initialize Hive.

As we will see in the next section, Hive works with the key-value scheme, where the value can be a primitive or a map.

Create basic structure in Hive

As with sharedpreferences, we must create a structure with which we can manage data persistently; In Hive, where we store the data, they are known as "boxes" which have a name to track and with this, obtain and establish data:

class MyListService {
  static MyListService? _instance;
  final String boxName = 'myList';
  MyListService._();
  static MyListService get instance {
    if (_instance == null) {
      _instance = WatchlistService._();
    }
    return _instance!;
  }
}

With the previous structure, we create a single instance which we access to manage our data; the next step is to define the methods to store the data; This first method allows you to create a new record for an item or update if the ID exists:

Future<void> addToMyList(int id, Map<String, 
    dynamic> item) async {
  final box = await Hive.openBox<Map<String, 
      dynamic>>(boxName);
  if (box.get(id) == null) {
    box.put(id, item);
  }
}

The previous code allows us to open the box, so that we can manage it, in this case, pub the item using the ID.

To remove an item from hive, we have:

Future<void> removeFromMyList(int id) async {
  final box = await Hive.openBox(boxName);
  box.delete(id);
}

Also, we can create a method that checks if an item is in the list using the ID:

Future<bool> isInMyList(int id) async {
  final box = await Hive.openBox(boxName);
  return box.containsKey(id);
}

Finally, we have a method to get all the data from the list:

Future<Iterable<Map<String, dynamic>>> geMylist() async {
  Final box = await Hive.openBox<Map<String, 
      dynamic>>(boxName);
  return box.values;
}

These are just some methods that you can create, but there are others that you can define as you wish according to your needs.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.