How to get sum of a field using Flutter/Dart?

Hi, I’m using Realm as a database for a Flutter app that I’m working on. I want to the sum of a field called duration for all entries between two specified times.

I’ve looked through the documentation and it definitely seems possible, but I can’t figure out how to integrate it into my Flutter app.

At the moment, I’m getting all the entries like this:

var results = db.query<Entry>(
        "startTime BETWEEN {\$0, \$1} SORT(startTime DESC)",
        [startDate, endDate]).toList();

where startDate and endDate are two DateTime variables set previously.

Since I can’t figure out how to sum the duration field, I’m simply foreaching through the list and adding up the duration the long way. But I’m sure there is a way to do this in Realm - I just can’t figure it out.

I’m afraid the Dart SDK don’t support aggregates yet :pensive:. If you add an index on startTime then the following should be fairly efficient:

import 'package:realm_dart/realm.dart';

part 'sum_duration.g.dart';

@RealmModel()
class _Stuff {
  @Indexed()
  late DateTime startTime;

  late int durationInMilliseconds;
  Duration get duration => Duration(milliseconds: durationInMilliseconds);
  set duration(Duration value) => durationInMilliseconds = value.inMilliseconds;
}

void main(List<String> arguments) {
  final realm = Realm(Configuration.local([Stuff.schema]));

  final begin = DateTime.fromMillisecondsSinceEpoch(0);
  final end = DateTime.now();

  final results =
      realm.query<Stuff>(r'startTime between {$0, $1}', [begin, end]);
  final sum = results.fold(Duration.zero, (acc, i) => acc + i.duration);

  print(sum);
}

Thank you very much for your help.

I’m afraid the Dart SDK don’t support aggregates yet

Do you know if this functionality is coming to Dart?

Yes, but I cannot promise when

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.