본문 바로가기
개발/Flutter

Flutter hive 원하는 model 넣기

by dev_caleb 2022. 11. 25.
728x90

나도 처음에 자료가 많이 없어서 당황했었는 데.. 

hive에는 modelList를 넣을 수가 있다..

 

마치 firebase에 firestore처럼 말이지.

 

 일단  sharedPref 나 Getstorage랑 비슷한 개념으로 보면 되는데

거기서는 int 나 String, map, list 이런 걸 가져올 수 있다.

마찬가지로 hive에서도 그렇게 가져올 수 있다. 

그런데 hive는 adapter라는 것을 통해서 model까지도 get으로 가져오고 put ,add 로 추가할 수 있다는 장점이 있다.

차하.. 그러면 우선 어떤걸 해줘야할까

 

https://docs.hivedb.dev/#/

 

Hive Docs

 

docs.hivedb.dev

 

hive doc를 보자. 원래 뭔가를 할 때 document를 보는 습관을 들이는 것이 좋다. 왜 이렇게 되고 원리를 파악하면 거의 먹고 들어가는 것 같다.

 

암튼 doc을 어느정도 보고 나서 해본 결과.. 

 

나는 MatjipModel이라는 모델로 리스트를 만들 것이고, 그 모델은 각각의 uid 키 값으로 저장할 것이다.

 

본인은 getxService를 쓰는데..  어떤 클래스 든 상관없을 것 같다. manager나 암튼 첨에 동작할 때 켜지는 클래스에서

 

late Box<MatjipModel> matjipBox;

만들어줬다. 

 

///Hive 내부 db를 사용하기 위한 initializing
await Hive.initFlutter();
Hive.registerAdapter(MatjipModelAdapter());
Hive.registerAdapter(TimestampAdapter());
Hive.registerAdapter(GeoPointAdapter());
Hive.registerAdapter(GeoFirePointAdapter());
matjipBox = await Hive.openBox<MatjipModel>('internalMatjip');

자 이렇게 어뎁터를 해가지고 가져오고

 

쓰기 , 업데이트

//추가
Get.find<SettingsService>()
    .matjipBox
    .put(matjipModel.matjipid!, matjipModel);

읽기

void onReadMatjipList() {
  logger
      .d('onReadMatjipList ${Get.find<SettingsService>().matjipBox.length}');
  logger.i(Get.find<SettingsService>().matjipBox.values.toString());
}

일단 박스만 지정해서 저장해놓으면 그 박스 안에 함수가 다 있어서 편하게 쓸 수 있다.

 

근데 중요한 건 이.. 저장을 하는게 어렵다는 사실.

 

그러면 -> 어떻게 저장을 할 것이냐.. 아까 그 adapter를 만들어줘야하는데 

 

대충 요롷게.. HiveObject를 extend 해가지고 field에 numbering을 해주면 HiveObject에서 제공하는 다양한 함수도 사용할 수 있고,

자동으로 Adapter를 만들어준다. 그런데 예를들어 이안에 들어가 있는 TimeStamp 등 3rd party library class 에 대해서는 따로 adapter를 만들어줘야한다. 

https://dev-caleb.tistory.com/302

 

flutter hive unknown type error

write 하는데 오류가 나서 좀 찾아봤다. 나중에 업데이트 할 때 참고해서 오류 수정해야겠다 https://github.com/hivedb/hive/issues/421 hive error: cannot write, unknown type: Timestamp. How to generate TypeAdapter for object typ

dev-caleb.tistory.com

 

되어서 너무 행복하다.

 

728x90