본문 바로가기
개발/Flutter

How to query flutter hive data ?

by dev_caleb 2022. 12. 17.
728x90

 

 

 

 

List<MatjipModel> matjipList({String? queryText}) {
  if (_matjipBox == null) {
    logger.e('박스 생성 실패');
    return [];
  } else {
    if (queryText == null) {
      return _matjipBox!.values.toList();
    } else {
      Set<MatjipModel> resultSet = {};
      resultSet.addAll(_matjipBox!.values.where((element) => element.description?.contains(queryText) ?? false));
      resultSet.addAll(_matjipBox!.values.where((element) => element.name.contains(queryText)));
      resultSet.addAll(_matjipBox!.values
          .where((element) => element.tags.indexWhere((e) => (e.toString()).contains(queryText)) != -1)); //tag list string에서 contain하고 있는것이 있는 지 확인
      resultSet.addAll(_matjipBox!.values.where((element) => element.geo.address?.contains(queryText) ?? false));
      return resultSet.toList();
    }
  }
}

 

 

but this solution has some problem..

if you query 'busan coffee', it will find data which contain exactly have 'busan coffee' word.

So I fixed my coding.

 

Set<MatjipModel> resultSet = {};
List<String> queryList = queryText.split(' ');
//쿼리를 둘 다 가지고 있어야 함..
List<Set<MatjipModel>> querySets = List.generate(queryList.length, (index) => {});
for (int i = 0; i < queryList.length; i++) {
  String query = queryList[i].trim();
  querySets[i].addAll(_matjipHiveBox!.values.where((element) => element.description?.contains(query) ?? false));
  querySets[i].addAll(_matjipHiveBox!.values.where((element) => element.name.contains(query)));
  querySets[i].addAll(_matjipHiveBox!.values
      .where((element) => element.tags.indexWhere((e) => (e.toString()).contains(query)) != -1)); //tag list string에서 contain하고 있는것이 있는 지 확인
  querySets[i].addAll(_matjipHiveBox!.values.where((element) => element.geo.address?.contains(query) ?? false));
}
resultSet = querySets.fold<Set<MatjipModel>>(querySets.first.toSet(), (a, b) => a.intersection(b.toSet()));
return resultSet.toList();

 

728x90