Filter and sort records from Hive box in Flutter

2,114

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']));
Share:
2,114
user2398514
Author by

user2398514

Updated on December 27, 2022

Comments

  • user2398514
    user2398514 over 1 year

    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

    • Randal Schwartz
      Randal Schwartz about 3 years
      so that value is a List<Map<String,Map<String,String>>> ? Or is the top level just the Map with keys like abc123. What is it you want to reorder... Maps don't have a sort. :)
    • Abion47
      Abion47 about 3 years
      Hive doesn't yet support sorting and filtering natively. If you want to do this, you will have to manually do it yourself in code.