Filter and sort records from Hive box in Flutter

Viewed 3325

Im using Hive with Flutter to store contacts with key as alphanumeric string, each contact data is a map with timestamp in it

Box Rows =

Key.     => Value  
'abc123' => {'name': 'JK', 'country':'GB', 'timestamp': '568'},
'etergb' => {'name': 'FS', 'country':'DE', 'timestamp': '425'}
'546hfg' => {'name': 'TD', 'country':'GB', 'timestamp': '687'}

Now is it possible to filter these with where country=GB condition and sort the rows by map.item.timestamp ASC/DESC

2 Answers

Filter

final hiveBox = Hive.box<Dynamic>('<BOX_NAME>');
List values = hiveBox.values.toList();

filtered = box.values
  .where((object) => object['country'] == 'GB')
  .toList();

Sort

filtered.sort((a, b) => a['timestamp'].compareTo(b['timestamp']));

For filtering, you can use For loop or Map.

You can perform the sort. Below is an example.

var items = box.values.toList();
items.sort((a, b) => a.name.compareTo(b.name)); //ASC
items.sort((b, a) => a.name.compareTo(b.name)); //DESC


@HiveType(typeId: 0)
class CategoryModel extends HiveObject {
  @HiveField(0)
  String id;

  @HiveField(1)
  String name;

  //...
  
  CategoryModel(this.id, this.name);
}
Related