Hive is a fast, lightweight, NoSQL database, for flutter and dart apps. Hive is really useful if you want a simple key-value database, without many relations, and really easy to use.
To do the CRUD operations we’ll be using a simple inventory app, where you can create inventory items, update and delete them when you want to. For ease, I’ve set up the project and put it on Github in the starter folder, it contains the UI and the provider setup.
Type Adapters
Hive allows you to store most standard types — String, int, Map, List, DateTime, but most times you want to have a model class for your data because this makes development much easier and faster. In order to use these model types, you need to register TypeAdapters which helps you encode/decode your object to binary form on disk. You can write your Type Adapters manually, but we’ll just be generating ours with the hive_generator and build_runner packages we added to our dev dependencies earlier.
First import hive
Add ‘inventory_model.g.dart’ as a part (this is where the typeadapter is generated)
Annotate the model class with @HiveType(), so the generator knows this should be a TypeAdapter.
Annotate each field you want to save with @HiveField(index), the index is an int and each index should appear once and you shouldn’t change it after registering them.
After generating the type adapters, you may get an error about some missing implementations: Missing concrete implementation of ‘getter TypeAdapter.typeId’. you can fix this by overriding the getter - typeId and returning an integer (also unique like HiveField) I use 0 in my case because this is my first type adapter.
Finally, register the type adapter in your main function, just add it beneath your hive initialization.

#flutter #mobile #database #dart #programming

Storing Local Data with Hive (and provider) in Flutter
35.35 GEEK