Hive: How to sort/orderBy a box?

Created on 9 Dec 2020  路  2Comments  路  Source: hivedb/hive

Hey all, what's the best practice to sort/order a box by a key?

model:

@HiveType(typeId: 0)
class GameResult extends Equatable {
  @HiveField(0)
  final DateTime dateTime;
  @HiveField(1)
  final int level;
  @HiveField(2)
  final double points;

  GameResult({
    @required this.dateTime,
    @required this.level,
    @required this.points,
  });

  @override
  List<Object> get props => [dateTime, level, points];
  @override
  bool get stringify => true;
}

Actually i'm opening the Box with

await Hive.openBox('game_results);

and then have a ListView like

final gameResults = Hive.box('game_results');

return ListView.builder(
  itemCount: gameResults.length,
    itemBuilder: (context, index) {
      final result = gameResults.getAt(index) as GameResult;

        return ListTile(
           title: Text((DateFormat('EEEE, dd.MM.yyy, HH:mm').format(result.dateTime)toString()),),


           subtitle: Text(
             'Level: ${result.level} - Punkte: ${result.points}',
              style: TextStyle(color: Colors.white)),
                 );
  });

Now i want to order/sort the List with the dateTime values.

Thanks in advance.

question

Most helpful comment

Try using...

final myList = box.values;
myList.sort((a, b) => a.property.compareTo(b.property));

...before the list view, pass myList.length to itemCount and access it with myList[index]

All 2 comments

Try using...

final myList = box.values;
myList.sort((a, b) => a.property.compareTo(b.property));

...before the list view, pass myList.length to itemCount and access it with myList[index]

Ah, easy, thanks 馃憤

short note: final myList = box.values._toList()_;

Was this page helpful?
0 / 5 - 0 ratings