Search code examples
flutterdartflutter-isar

How to use .max() aggregate function in Isar database for Flutter?


I am learning how to use Isar database for my Flutter app. I am trying to get the maximum value of a column. The Isar documentation suggests that I can use the .max() aggregate function but does not give an example on how to actually use it in a query.

Below is the code I have. I would like someone to suggest what I put in place of <rest_of_query_here>. I tried putting it after .where(), .filter(), even after .findAll() but none is acceptable.

part 'client.g.dart';

@collection
class Client {
  Id id = Isar.autoIncrement; // you can also use id = null to auto increment

  @Index(type: IndexType.value)
  String? clientId; // actually a number of the form '10001','10002',...

  String? lastname;
  String? firstname;
}

...
// We should use .max() somewhere in the query
Future<String> getMaxClientId() async {
  final isar = await Isar.open([ClientSchema]);
  final clientId = await isar.clients.<rest_of_query_here>;
  return clientId == null ? '10000' : clientId;
}
...


Solution

  • According to this documentation, you need to run a property query to use the .max() operation. A property query isolates and returns a single property (or column if thinking in SQL terms) which you can then run aggregate operations on such as .max(), .min(), .sum(), .average().

    For your example replace the <rest_of_query_here> line with the following:

    final clientId = await isar.clients.where().clientIdProperty().max();