Flutter/Package

[Flutter] Hive

찌김이 2022. 7. 26. 17:03
728x90
반응형

Flutter Local DB 중에서는 Sqlflite, Drift 처럼 RDBMS 만 있는게 아닌 NoSql 도 존재합니다.

Nosql 형태인 Hive 에 대해서 간단하게 포스팅 하려고 합니다.

 

hive | Dart Package

Lightweight and blazing fast key-value database written in pure Dart. Strongly encrypted using AES-256.

pub.dev

 

pubspec.yaml

dependencies:
  hive: ^2.2.3
  hive_flutter: ^1.1.0
  
dev_dependencies:
  build_runner: ^2.2.0
  hive_generator: ^1.1.3

 

hive_todo.dart

  • HiveObject 를 상속 후 클래스를 작성해줍니다.
  • 터미널에  flutter pub run build_runner build 를 입력하면 hive 관련 코드가 만들어집니다.
import 'package:hive/hive.dart';

part 'hive_todo.g.dart';

@HiveType(typeId: 0)
class HiveTodo extends HiveObject {
  @HiveField(0)
  int id;

  @HiveField(1)
  String title;

  @HiveField(2)
  bool done;

  HiveTodo({
    required this.id,
    required this.title,
    required this.done,
  });
}
flutter pub run build_runner build

 

main.dart

  • main() 에 async 를 붙여주시고 Hive 관련 코드를 넣어줍니다.
void main() async {
	
  // 추가
  await Hive.initFlutter();
  Hive.registerAdapter(HiveTodoAdapter());
  await Hive.openBox<HiveTodo>('myBox');
  
  runApp(const MyApp());
}

 

hive_screen.dart

  • 예시 화면입니다. 간단한 CRUD 만 구현해봤습니다.
import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:uuid/uuid.dart';

import 'model/hive_todo.dart';

class HiveScreen extends StatefulWidget {
  const HiveScreen({Key? key}) : super(key: key);

  @override
  State<HiveScreen> createState() => _HiveScreenState();
}

class _HiveScreenState extends State<HiveScreen> {
  Box<HiveTodo> _box = Hive.box<HiveTodo>('myBox');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'Hive Sample Page',
        ),
      ),
      body: ValueListenableBuilder(
        valueListenable: _box.listenable(),
        builder: (BuildContext context, Box<HiveTodo> todos, _) {
          if (todos.values.isEmpty) {
            return const Center(
              child: Text(
                'Todo is empty',
                style: TextStyle(
                  fontSize: 20.0,
                ),
              ),
            );
          }

          return ListView(
            children: todos.values
                .toList()
                .reversed
                .map(
                  (e) => ListTile(
                    title: Text('${e.title} ${e.key}'),
                    leading: updateBtn(e),
                    trailing: deleteBtn(e.key),
                  ),
                )
                .toList(),
          );
        },
      ),
      floatingActionButton: addBtn(),
    );
  }

  Widget deleteBtn(dynamic key) => IconButton(
        onPressed: () {
          setState(() {
            _box.delete(key);
          });
        },
        icon: const Icon(Icons.delete_forever),
      );

  Widget updateBtn(HiveTodo todo) => IconButton(
        onPressed: () {
          setState(() {
            var title =
                todo.title.contains('update') ? 'title' : 'update title';

            var hiveTodo = HiveTodo(
              id: todo.id,
              title: title,
              done: false,
            );

            _box.put(todo.key, hiveTodo);
          });
        },
        icon: const Icon(Icons.update_sharp),
      );

  FloatingActionButton addBtn() => FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          setState(() {
            var id = Uuid().v4();
            var todo = HiveTodo(id: id, title: 'title', done: true);
            _box.add(todo);
          });
        },
      );
}
728x90
반응형