cph-cachet / flutter-plugins

A collection of Flutter plugins developed by CACHET
550 stars 678 forks source link

[Health 11.1.0] Data duplication issue with entries from multiple devices #1074

Open HassanAlyousef opened 2 weeks ago

HassanAlyousef commented 2 weeks ago

Hello everyone,

I hope all is well with you. I’ve been working with the health plugin for a while now, I've been testing the features with my data, which its source is only my iPhone. One feature sums up the entries for a specific data type for the current day and display them. I used the method below, and it seems to work just fine.

  double _getHealthDataValueToday(HealthDataType type) {
    num totalValue = 0;
    DateTime now = DateTime.now();
    DateTime startOfDay = DateTime(now.year, now.month, now.day, 0, 0, 0);
    DateTime endOfDay = DateTime(now.year, now.month, now.day, 23, 59, 59);

    List<HealthDataPoint> todayData = widget.healthDataList.where((dataPoint) {
      DateTime dataPointStart = dataPoint.dateFrom.toLocal();
      return dataPointStart.isAfter(startOfDay) &&
          dataPointStart.isBefore(endOfDay) &&
          dataPoint.type == type &&
          dataPoint.value is NumericHealthValue;
    }).toList();

    for (var dataPoint in todayData) {
      totalValue += (dataPoint.value as NumericHealthValue).numericValue;
    }

    return totalValue.toDouble();
  }

However, after launching a new TestFlight version, a reported issue indicated that the data was significantly higher than what is shown in Apple’s Health app. After some digging, It looks like some entries are counted twice because they come from more than one source, like an iPhone and an Apple Watch.

I thought the removeDuplicates method would take care of these kind of duplications, but it turns out it only removes entries that are exactly the same in everything, which isn’t really what I was looking for.

Does anyone have an idea on how to tweak my method to avoid counting duplicates? Also, I noticed that the total in my app doesn’t always match the total in Apple Health, even though my math checks out when I add up the entries in the Health app myself. Does anyone know why this might be happening? What method does Apple use for their calculations? Why are some entries left out of their total, even though they all come from one source which is my iPhone? Any help or insight would be great. Thanks!