Hive is a lightweight and blazing fast key-value database

Overview

Hive Manager

Hive is a lightweight and blazing fast key-value database

Features

  • Cross platform -> mobile, desktop
  • Performance
  • Strong encryption built in

More details in https://pub.dev/packages/hive

Implementation

You should add these packages into pubspec.yaml file like in the screenshot

s1

You can store values as key-value or as a hive object. If you want to store values as an object, you need to define a class that must extends HiveObject and HiveUserObject has a hive type and each variable defined as a hive field.

import 'package:hive/hive.dart';

part 'hive_user.g.dart';

@HiveType(typeId: 1)
class HiveUserObject extends HiveObject {
  @HiveField(0)
  int? userId;
  @HiveField(1)
  String? firstName;
  @HiveField(2)
  String? surname;
  @HiveField(3)
  String? userName;
  @HiveField(4)
  String? email;

  HiveUserObject(
      {this.userId, this.firstName, this.surname, this.userName, this.email});

  HiveUserObject.fromJson(Map
   
     json) {
    userId = json['userId'];
    firstName = json['firstName'];
    surname = json['surname'];
    userName = json['userName'];
    email = json['email'];
  }

  Map
    
      toJson() {
    final Map
     
       data = 
      
       {};
    data['userId'] = userId;
    data['firstName'] = firstName;
    data['surname'] = surname;
    data['userName'] = userName;
    data['email'] = email;
    return data;
  }
}

      
     
    
   

After this part, you need to start hive database in main method

void main() async {
  await HiveManager.preferencesInit();
  runApp(HomePage());
}

Run these command flutter pub get flutter packages pub run build_runner

After running these command, the type adapter will be created because you defined type adapter in hive object class (part 'hive_user.g.dart');

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'hive_user.dart';

// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************

class HiveUserObjectAdapter extends TypeAdapter
   
     {
  @override
  final int typeId = 1;

  @override
  HiveUserObject read(BinaryReader reader) {
    final numOfFields = reader.readByte();
    final fields = 
    
     {
      for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
    };
    return HiveUserObject(
      userId: fields[0] as int?,
      firstName: fields[1] as String?,
      surname: fields[2] as String?,
      userName: fields[3] as String?,
      email: fields[4] as String?,
    );
  }

  @override
  void write(BinaryWriter writer, HiveUserObject obj) {
    writer
      ..writeByte(5)
      ..writeByte(0)
      ..write(obj.userId)
      ..writeByte(1)
      ..write(obj.firstName)
      ..writeByte(2)
      ..write(obj.surname)
      ..writeByte(3)
      ..write(obj.userName)
      ..writeByte(4)
      ..write(obj.email);
  }

  @override
  int get hashCode => typeId.hashCode;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is HiveUserObjectAdapter &&
          runtimeType == other.runtimeType &&
          typeId == other.typeId;
}

    
   

In the Hive Manager, you need to give your type adapter in preferencesInit method and if you define another hive object, you need to organise methods (add, get...) as below

static preferencesInit() async {
    await Hive.initFlutter();

    final appDocumentDir = await getApplicationDocumentsDirectory();

    Hive
      ..init(appDocumentDir.path)
      ..registerAdapter(HiveUserObjectAdapter());

    await openBox();
    return;
  }
Future
   
     addUser(HiveUserObject user) async {
    await _db[1].add(user);
  }

  Future
    
      updateUser(HiveUserObject user, int index) async {
    await _db[1].putAt(index, user);
  }

  HiveUserObject getUser(int index) => _db[1].getAt(index);

    
   

If you want to store values as key-value, you need to create a enum that include any information you want to store

enum HiveKeys {
  USERID,
  USERNAME,
  FIRSTNAME,
  SURNAME,
  EMAIL,
  PHONE,
}

How to use?

  • Store as key-value
await HiveManager.instance.setIntValue(HiveKeys.USERID, form.userId!);
await HiveManager.instance.setStringValue(HiveKeys.FIRSTNAME, form.firstName!);
await HiveManager.instance.setStringValue(HiveKeys.SURNAME, form.surname!);
await HiveManager.instance.setStringValue(HiveKeys.USERNAME, form.userName!);
await HiveManager.instance.setStringValue(HiveKeys.EMAIL, form.email!);
  • Store as an object
final HiveUserObject _hiveUserObject = HiveUserObject();
_hiveUserObject.userId = 0;
_hiveUserObject.firstName =  "Okan";
_hiveUserObject.surname = "Rüzgar";
_hiveUserObject.username =  "Vasseurr";
_hiveUserObject.email =  "[email protected]";

//save user as an object
HiveManager.instance.addUser(hiveUserObject);
  • Get values as key-value
Column(
  mainAxisAlignment: MainAxisAlignment.start,
  children: [
    const Text("Get User Info with key-value"),
    userField("User Id", HiveManager.instance.getIntValue(HiveKeys.USERID), context),
    userField("Username", HiveManager.instance.getStringValue(HiveKeys.USERNAME), context),
    userField("First Name", HiveManager.instance.getStringValue(HiveKeys.FIRSTNAME), context),
    userField("Surname", HiveManager.instance.getStringValue(HiveKeys.SURNAME), context),
    userField("E-mail", HiveManager.instance.getStringValue(HiveKeys.EMAIL), context),
    ],
),
  • Get values as an object
Column(
  mainAxisAlignment: MainAxisAlignment.start,
  children: [
    const Text("Get User Info with object"),
    userField("User Id", HiveManager.instance.getUser(0).userId, context),
    userField("Username", HiveManager.instance.getUser(0).userName!, context),
    userField("First Name", HiveManager.instance.getUser(0).firstName!, context),
    userField("Surname", HiveManager.instance.getUser(0).surname!, context),
    userField("E-mail", HiveManager.instance.getUser(0).email!, context),
    ],
),
You might also like...

Hive Wait provide a Hive repository to calling methods in the box as async.

Hive Wait provide a Hive repository to calling methods in the box as async.

May 10, 2022

Music Player app made with Just audio library and Local database Hive.

Music Player app made with Just audio library and Local database Hive.

Music Player app made with Just audio library and Local database Hive. Find the free and Royelty music with Happy Rock application. The app contains information about singers and you can make your own playlist with Songs.Happy rock App's features are same as the real music app like spotify, amazon music etc.

Dec 22, 2022

Flutter shopping app with Getx for State management, Dio for APIs and Hive for the local database.

Flutter shopping app with Getx for State management, Dio for APIs and Hive for the local database.

Created By Sajjad Javadi Email: [email protected] Show some ❤️ and star the repo to support the project Flutter Shopping app example In this pr

Nov 23, 2022

Persist data with Flutter's Hive NoSQL Database locally on Android, iOS & Web.

Persist data with Flutter's Hive NoSQL Database locally on Android, iOS & Web.

Flutter Tutorial - Hive NoSQL Database Persist data with Flutter's Hive NoSQL Database locally on Android, iOS & Web. ✌  Preview App Preview Course Pr

Dec 31, 2022

GoodBudget - A budget monitor or expense tracker Flutter application that persists data with Hive NoSQL database.

GoodBudget - A budget monitor or expense tracker Flutter application that persists data with Hive NoSQL database.

GoodBudget - A budget monitor or expense tracker Flutter application that persists data with Hive NoSQL database. This cross platform application is available on Android, iOS & Web. Both expenses and income are monitored.

Sep 19, 2022

Super Fast Cross Platform Database for Flutter & Web Apps

Super Fast Cross Platform Database for Flutter & Web Apps

Isar Database 🚧 Alpha version - Use with care. 🚧 Quickstart • Documentation • Sample Apps • Support & Ideas • Pub.dev Isar [ee-zahr]: River in Bavar

Jan 1, 2023

library to help you create database on local memory, support json local database inspired by lowdb

Licensed Licensed under the MIT License http://opensource.org/licenses/MIT. SPDX-License-Identifier: MIT Copyright (c) 2021 Azkadev http://github.c

Oct 17, 2022

NETCoreSync is a database synchronization framework where each client's local offline database

NETCoreSync NETCoreSync is a database synchronization framework where each client's local offline database (on each client's multiple devices) can be

Oct 31, 2022

A flutter plugin to play Youtube Videos without API Key in range of Quality(144p, 240p,360p,480p,720p and 1080p).

Youtube Player Plugin This plugin is discontinued. Please use youtube_player_flutter which is an officially provided way of playing youtube videos, su

Nov 13, 2022

Netflix app UI clone using bloc,Rest API and TMDB for API key

netflix_flutter project_using_bloc packages Used flutter_bloc json_serializable get_it dio A few resources to get you started if this is your first Fl

Nov 25, 2022

A degital diary with key feature of saving your thoughts with image

localstore A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if th

Nov 13, 2021

Aris keyunique - Use the Flutter Unique Key To Preserve the state of Stateful Widgets if they moved around in the Widget tree

Aris keyunique - Use the Flutter Unique Key To Preserve the state of Stateful Widgets if they moved around in the Widget tree

Flutter Tutorial - Flutter Keys - Unique Key Use the Flutter Unique Key To Prese

Dec 29, 2021

WIP: generate easy localization key code

Generates translation key code for the easy localization package. Support for json and yaml formats.You can see examples in the assets/ folder. Gettin

Oct 24, 2022

A simple app to demonstrate a testable, maintainable, and scalable architecture for flutter. flutter_bloc, hive, and REST API are some of the tech stacks used in this project.

A simple app to demonstrate a testable, maintainable, and scalable architecture for flutter. flutter_bloc, hive, and REST API are some of the tech stacks used in this project.

last_fm A simple app to demonstrate a testable, maintainable, and scalable architecture for flutter. flutter_bloc, hive, and REST API are some of the

Dec 31, 2022

Provider Demo - Simple Provider using provider update counter and apply a timer also increase and decrease that value by pressing buttons

Provider Demo - Simple Provider using provider update counter and apply a timer also increase and decrease that value by pressing buttons

state_management simple Provider using provider update counter and apply a timer

Feb 2, 2022

A flutter boilerplate project containing bloc, pedantic, hive, easy_translations and more!

A flutter boilerplate project containing bloc, pedantic, hive, easy_translations and more!

Flutter Production Boilerplate A flutter project containing bloc, flutter_lints, hive, easy_translations and more! This repository is the starting poi

Dec 26, 2022

Udemy Course "Dart and Flutter: The Complete Developer's Guide" Project. (With Hive DB)

Udemy-Course-Flutter Udemy Course "Dart and Flutter: The Complete Developer's Guide" Project. (With Hive DB) The course: https://www.udemy.com/course/

Jun 11, 2022

Flutter App Change Theme With Getx and Save Theme Stage with Hive

Flutter App Change Theme With Getx and Save Theme Stage with Hive

Flutter Change app Theme With GetX Flutter App Change Theme With Getx. Theme Stage saved using Hive. instead of hive you can use get-storage or shared

Oct 22, 2022

Flutter todo - Simple To-do application created with Flutter and Hive

Flutter todo - Simple To-do application created with Flutter and Hive

To-do app Simple To-do application created with Flutter and Hive. Description Fi

Jan 24, 2022
Owner
Okan
Okan
Generate dart type definitions from PostgreSQL database schema

schema-dart Generate dart type definitions from PostgreSQL database schema (WIP) Installation: Until the package is published to pub.dev, it can be in

null 8 Oct 31, 2022
Create a DataTable with Flutter to display data in columns, rows, and cells and also learn how to sort the data within the table.

Flutter Tutorial - Sortable DataTable Create a DataTable with Flutter to display data in columns, rows, and cells and also learn how to sort the data

Johannes Milke 22 Oct 9, 2022
:fire:GeoFlutterFire:fire: is an open-source library that allows you to store and query firestore documents based on their geographic location.

GeoFlutterFire ?? GeoFlutterFire is an open-source library that allows you to store and query a set of keys based on their geographic location. At its

Darshan N 282 Dec 11, 2022
his package provides a Clock class which encapsulates the notion of the "current time" and provides easy access to points relative to the current time.

This package provides a Clock class which encapsulates the notion of the "current time" and provides easy access to points relative to the current tim

Dart 34 Dec 15, 2022
Shared SQLite DB across mobile, web and desktop

moor_shared An example project to demonstrate how moor can be used on multiple platforms (Web, android, iOS, macOS, Windows and Linux). Note: You need

Rody Davis 143 Nov 28, 2022
Lightweight and blazing fast key-value database written in pure Dart.

Fast, Enjoyable & Secure NoSQL Database Hive is a lightweight and blazing fast key-value database written in pure Dart. Inspired by Bitcask. Documenta

HiveDB 3.4k Dec 30, 2022
Lightweight and blazing fast key-value database written in pure Dart.

Fast, Enjoyable & Secure NoSQL Database Hive is a lightweight and blazing fast key-value database written in pure Dart. Inspired by Bitcask. Documenta

HiveDB 3.4k Dec 30, 2022
A fast, extra light and synchronous key-value storage to Get framework

get_storage A fast, extra light and synchronous key-value in memory, which backs up data to disk at each operation. It is written entirely in Dart and

Jonny Borges 257 Dec 21, 2022
A reactive key-value store for Flutter projects. Like shared_preferences, but with Streams.

streaming_shared_preferences A reactive key-value store for Flutter projects. streaming_shared_preferences adds reactive functionality on top of share

Iiro Krankka 244 Dec 22, 2022
Local data hive - Local data hive for flutter

local_data_hive A new Flutter application. ScreenShot

Mehmet Emre ÖZ 0 Jan 8, 2022