-
[ Flutter ] Hive ( NoSql ) 추가, 수정, 삭제Application/Flutter 2024. 9. 1. 16:23반응형
Add
hive box에 데이터를 추가할 경우 단순하게 add를 통해 데이터를 추가 할 수 있다.
처음엔 기존 index값을 현재 _costBox의 length를 기준으로 해서 했지만
수정 삭제 기능이 들어가면서 index값이 계속 꼬여 수정이나 삭제가 다른 데이터에 적용되서 방식을 변경
void add(String title, String pay) { Cost cost = Cost(id: getNextId(_costBox), title: title, pay: pay); _costBox.add(cost); }
box가 비어있다면 0을 return하고
그 외는 현재 박스의 마지막 값의 id에서 +1 을 해주는 방식으로 index를 설정
int getNextId(Box box) { if (box.isEmpty) { return 0; } else { final lastItem = box.values.last; return lastItem.id + 1; } }
Update
update의 경우 덮어씌우는 방식으로 진행
변경되는 값의 id와 변경값을 가져와 Cost타입으로 다시 만들어주고
이후 put을 활용하여 해당 key값에 변경된 데이터를 덮어씌우는 방식으로 진행
void update(Cost cost) { Cost data = Cost(id: cost.id, title: cost.title, pay: cost.pay); _costBox.put(cost.id, data); }
put과 add의 차이는 add는 단순히 데이터 추가라면 put은 키값을 활용하여 데이터를 추가한다고 생각하면 편함
해당 key값이 존재하면 그 키값에 데이터를 새로 덮어씌우고 없다면 새로 해당 key값으로 데이터가 추가
Delete
삭제는 단순히 key값을 활용하여 데이터를 삭제
void delete(Cost cost) { _costBox.delete(cost.id); notifyListeners(); }
Use
만든 추가, 수정, 삭제 기능을 구현하기 위해
추가와 수정은 한곳에서 컨트롤하기 때문에 하나의 메서드만 호출하여 실행할 수 있도록 처리
void upsert(Cost param) { if (param.id != null) { update(param); } else { add(param.title, param.pay); } notifyListeners(); }
따라서 기존에 만든 bottomModal에서 저장을 누를시 해당 데이터로 Cost객체를 다시 정의
id값의 경우 존재 여부에 따라서 값을 넣고 없다면 null을 통해 id값의 존재 여부로 수정 사항인지 추가 사항인지 판단
Container SaveChildButton(BuildContext context) { final fixSaveProvider = Provider.of<FixSaveProvider>(context, listen: false); return Container( margin: const EdgeInsets.fromLTRB(0, 0, 16.0, 0), alignment: Alignment.centerRight, child: ElevatedButton( onPressed: () { Cost param = Cost( id: widget.cost?.id ?? null, title: _textController.text, pay: _payController.text); fixSaveProvider.upsert(param); Navigator.pop(context); }, style: ElevatedButton.styleFrom( backgroundColor: buttonColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(4)), elevation: 0), child: Text( '저장', style: TextStyle(color: textColor), )), );
이렇게 하면 upsert 메소드에서 id의 존재 여부에 따라서 추가 혹은 수정을 판단하여 진행된다
삭제의 경우에는 이전에 만든 alertDialog를 활용하여 true일 경우 실행이 되도록 세팅
Container( width: buttonSize, height: buttonSize, child: ElevatedButton( onPressed: () async { bool result = await showDialog( context: context, builder: (BuildContext context) { return CustomAlertDialog(); // 여기에서 다이얼로그를 표시 }, ); if (result) { fixSaveProvider.delete(cost); } }, style: ElevatedButton.styleFrom( backgroundColor: boxColor, elevation: 0, padding: const EdgeInsets.all(0.0), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(4.0))), child: SvgPicture.asset( 'assets/icons/trash.svg', color: red, width: buttonSize * 0.6, height: buttonSize * 0.6, ), ), ),
728x90반응형'Application > Flutter' 카테고리의 다른 글
[ Flutter ] Horizontal Scroll ListView, Global Key (0) 2024.09.08 [ Flutter ] OnBoarding (0) 2024.09.08 [ Flutter ] Alert Dialog (0) 2024.09.01 [ Flutter ] Slidable Custom (0) 2024.08.29 [ Flutter ] Hive ( NoSql ) 데이터 저장 (0) 2024.08.24