Hive Flutter, How to get values in reverse key order

Viewed 2010

I am using a library called Hive which is a very fast NoSQL database. I have everything set up and I am trying to get the values in reverse order (Last in First Out).

I have a box of entries, each entry has a creation date and an entry text. As you can see in the code that whenever an entry is created the date of it is "Now". I want to get the list of entries starting from the most recent entry (latest date). by default, the first entry added using box.add() will have a key of 0, the one after it is 1, and etc. In Hive's documentation, it says that fetching the values can be done "in reverse lexicographic order" but I wasn't able to figure it out.

Thanks in advance!

import 'package:hive/hive.dart';
part '../type_adapters/entry.g.dart';

@HiveType(typeId: 0)
class Entry extends HiveObject {
  @HiveField(0)
  String _entryText;
  @HiveField(1)
  DateTime _creationDate;
  Entry(this._entryText) {
    _creationDate = DateTime.now();
  }

  String get entryText => _entryText;
  DateTime get creationDate => _creationDate;

  @override
  String toString() {
    return "$_entryText, $_creationDate, $key";
  }
}

library link: Hive Hive Documentation

2 Answers

So I figured it out, you have to pass your own sorting function when opening the box. the default way that Hive does is:

/// Efficient default implementation to compare keys
int defaultKeyComparator(dynamic k1, dynamic k2) {
  if (k1 is int) {
    if (k2 is int) {
      if (k1 > k2) {
        return 1;
      } else if (k1 < k2) {
        return -1;
      } else {
        return 0;
      }
    } else {
      return -1;
    }
  } else if (k2 is String) {
    return (k1 as String).compareTo(k2);
  } else {
    return 1;
  }
}

their default function gets you values in lexicographic order. in order to reverse it, had to pass my own "keyComparator" (which is the function used to sort the values, it receives 2 keys and returns an int)

so when opening the box:

_entryBox = await Hive.openBox(ENTRY_BOX, keyComparator: _reverseOrder);

_reverseOrder function:

  int _reverseOrder(k1, k2) {
    if (k1 is int) {
      if (k2 is int) {
        if (k1 > k2) {
          return -1;
        } else if (k1 < k2) {
          return 1;
        } else {
          return 0;
        }
      } else {
        return -1;
      }
    }
  }

it gets a bit more complicated if you want to use start and end keys instead of getting all the values at once ( box.valuesBetween(startKey: , endKey:, ).

I know it's pretty late to add an answer to this threat. But I'm adding it if anyone else got stuck on this.

Hive doesn't support sorting. So the easiest way is to sort the list after getting the values out of the box.

entryList = entryBox.values;

Now sort the list before showing it on the UI.

entryList.sort((a, b) => -a._creationDate.compareTo(b._creationDate));

The (-) sign reverses the list from the most recent timestamp to the older one.

Related