ABOUT ME

-

  • [ Flutter ] Hive ( NoSql ) Setting
    Application/Flutter 2024. 8. 24. 16:58
    반응형

    이전 ture, false값으로 다크모드를 설정할때는 캐시 저장 방식을 사용했지만,

    데이터를 저장하기 위해서 캐시 저장방식이 불가하여 hive 라이브러리를 사용하여 데이터를 저장하는 방식으로 진행

     

    로컬로 데이터를 저장하기 위해서 다른 DB를 사용하지 않고 hive를 사용


    Hive Dependencies

    dependencies:
      flutter:
        sdk: flutter
      hive: ^2.2.3
      hive_flutter: ^1.1.0
      
     dev_dependencies:
      flutter_test:
        sdk: flutter
     uild_runner: ^2.4.7
     hive_generator: ^2.0.1

     

    hive를 사용하기위해

    hive, hive_flutter

    uild_runner, hive_generator를 추가


    Initalization

    void main() async {
      await Hive.initFlutter();
    
      runApp(const MyApp());
    }

    main.dart 에서 Hive.initFlutter를 사용하여 hive 초기화 진행

     

    데이터를 저장할 타입 클래스를 생성

    idx 와 title pay 3개의 데이터를 저장하기 위해 타입을 선언

    typeId는 데이터를 저장하고 검색하는데 사용되기에 저장할 객체는 아직 한개이므로 0으로 입력 이후 추가시마다 +1 씩 하여 id를 저장

    import 'package:hive_flutter/hive_flutter.dart';
    
    part 'cost.g.dart';
    
    @HiveType(typeId: 0)
    class Cost extends HiveObject {
      @HiveField(0)
      final int id;
    
      @HiveField(1)
      final String title;
    
      @HiveField(2)
      final String pay;
    
      Cost({
        required this.id,
        required this.title,
        required this.pay,
      });
    }

     

    part 'cost.g.dart'를 사용하기위해 cost.g.dart파일을 생성

    아래의 명령어를 실행하면 생성이 된다. ( 파일명.g.dart ) 형식으로 생성이 되므로 유의

    flutter pub run build_runner build

     

    이후 main에서 adapter를 연결

    adapter는 사용자가 정의한 객체를 저장해야할 경우 무조건 등록

    void main() async {
      await Hive.initFlutter();
    
      Hive.registerAdapter(CostAdapter());
    
      runApp(const MyApp());
    }

    BoxOpen

    hive를 사용하기 위해서 우선 box를 열어야한다.

    box는 hive가 데이터를 저장하기 위한 공간으로써 저장 혹은 수정을 할경우 box가 열려 있어야 가능하다

     

    provider를 통해 저장 혹은 수정을 할 예정이기에

    provider가 처음 생성된 시점에서 box를 open

    이후 빈 리스트를 생성하여 box에 저장된 값을 리스트에 옮겨 사용

     

    이후 get을 사용하여 다른 컴포넌트에서 fixedCost 배열을 쓸 수 있도록 처리

    class FixSaveProvider extends ChangeNotifier {
      late Box<Cost> _costBox;
      List<Cost> fixedCost = [];
    
      FixSaveProvider() {
        _initBox();
      }
    
      Future<void> _initBox() async {
        _costBox = await Hive.openBox<Cost>('costBox');
        fixedCost = _costBox.values.toList();
        notifyListeners();
      }
    
      List<Cost> get getFixedCost => fixedCost;

     

    추가 및 삭제는 이후 하나씩 차례로 다루고자 함

    728x90
    반응형