Hive In Flutter

Made for Zemin Istanbul Presantation

Basically, the application saves the basic data types and custom generated data classes to the local storage.

Getting Started

Dependencies 馃О


  hive_flutter: ^1.1.0 //add this line

  build_runner: ^2.2.1 //add this line
  hive_generator: ^1.1.3 //add this line
  • hive_flutter

Provides operations on the local storage.

  • build_runner

Provides a concrete way of generating files using Dart code.

  • hive_generator

Provides automatic generation of TypeAdapters for almost any class.

Project Architecture Output

鈹溾攢鈹 lib                  
    鈹溾攢鈹 core
        鈹斺攢鈹 service
            鈹溾攢鈹 cache
                鈹溾攢鈹 base_cache_manager.dart
                鈹斺攢鈹 cache_enums.dart   
    鈹溾攢鈹 model
        鈹溾攢鈹 todo_model.dart
        鈹斺攢鈹 todo_model.g.dart
    鈹斺攢鈹 product
        鈹斺攢鈹 todo
            鈹溾攢鈹 todo_service.dart
            鈹斺攢鈹 todo_view.dart
鈹斺攢鈹 main.dart

Base Functions & Hive Classes

Base Functions

  • Initialize Hive
  await Hive.initFlutter();
  • Open Hive Box

Future<void> boxInit() async {
  await Hive.openBox(boxName);
  • Add item to box with auto increment key

Future<void> addItemWithAutoIncrementKey(T item) async {
  await _box!.add(item);
  • Add item to box with custom key

Future<void> addItemWithCustomKey(dynamic key, T item) async {
  await _box!.put(key, item);
  • Get item from box

T? getItem(dynamic key) {
  return _box!.get(key);
  • Remove item from box

Future<void> removeItem(dynamic key) async {
  await _box!.delete(key);
  • Clear box

Future<void> clearBox() async {
  await _box!.clear();
  • Close box

Future<void> closeBox() async {
  await _box!.close();

Hive Classes

  • Class Architecture

import 'package:hive_flutter/adapters.dart';
part 'todo_model.g.dart';

@HiveType(typeId: 1)
class Todo {
  int? userId;
  int? id;
  String? title;
  bool? completed;

  Todo({this.userId,, this.title, this.completed});

  Todo.fromJson(Map<String, dynamic> json) {...}
  Map<String, dynamic> toJson() {...}
  • Generate Part File Command
flutter pub run build_runner build

Create an Manager from Generic Cache Manager

  • initialize

final BaseCacheManager<Todo> _todoCacheManager = BaseCacheManager<Todo>(boxName: CacheBoxNames.todo);
Future<void> serviceInit() async {
  await _todoCacheManager.boxInit();

Usage 馃洜

When the manager is generated and initialized, it can accesses and uses generic cache manager functions.

await _todoCacheManager.boxInit();
await _todoCacheManager.addItemList(items);
await _todoCacheManager.clearBox();


Hive Documentation


View Github

Entradas similares

Deja una respuesta