free geoip
38

Local Storage with Hive in Flutter Apps

Storing data locally in Flutter applications is crucial for building fast and responsive mobile apps. One of the most efficient…

Storing data locally in Flutter applications is crucial for building fast and responsive mobile apps. One of the most efficient ways to implement local storage in Flutter is by using the Hive database. Hive is a lightweight, blazing-fast key-value database that runs natively on mobile and desktop platforms without any additional dependencies.

Local Storage with Hive Database

In this article, you’ll learn how to use Hive for local storage in Flutter with a complete source code example. We will explore the setup, model class creation, adapter generation, and the proper way to read, write, and delete data using Hive.

What is Hive Database?

Hive is a NoSQL database designed specifically for Flutter. It is ideal for small datasets, offline applications, and situations where performance is critical. Hive offers type safety and is 100% Dart-native.

Learn more about Hive from the official documentation.

Step-by-Step Guide

1. Add Hive Dependencies
dependencies:
  hive: ^2.2.3
  hive_flutter: ^1.1.0
  path_provider: ^2.1.2

dev_dependencies:
  hive_generator: ^2.0.1
  build_runner: ^2.4.7

2. Model Class (User.dart)

import 'package:hive/hive.dart';

part 'user.g.dart';

@HiveType(typeId: 0)
class User extends HiveObject {
  @HiveField(0)
  String name;

  @HiveField(1)
  int age;

  User({required this.name, required this.age});
}

3. Register Adapter (main.dart)

import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'user.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();
  Hive.registerAdapter(UserAdapter());
  await Hive.openBox<User>('userBox');
  runApp(MyApp());
}=

4. Write Data (write_user.dart)

import 'package:hive/hive.dart';
import 'user.dart';

Future<void> addUser(User user) async {
  var box = Hive.box<User>('userBox');
  await box.add(user);
}

5. Read Data (read_user.dart)

import 'package:hive/hive.dart';
import 'user.dart';

List<User> getUsers() {
  var box = Hive.box<User>('userBox');
  return box.values.toList();
}

6. Delete Data (delete_user.dart)

import 'package:hive/hive.dart';
import 'user.dart';

Future<void> deleteUser(int index) async {
  var box = Hive.box<User>('userBox');
  await box.deleteAt(index);
}

Benefits of Using Hive:

  • Extremely fast for read/write operations.
  • No native dependencies required.
  • Supports custom objects using TypeAdapters.
  • Lightweight and easy to integrate.

Hive is a great choice when you need a powerful and simple local database for Flutter. By following the steps above, you can implement complete local storage functionalities using Hive with ease.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *