如何使用健康包flutter从google fit获取每月步数数据

问题描述 投票:0回答:2

我正在编写一个 flutter 程序来使用 Health 包接收来自 google fit 的数据,我能够获取每周数据

       weeklyStepData = await health.getTotalStepsInInterval(
            now.subtract(const Duration(days: 7)), now);

但是当我尝试获取每月数据时

        final yesterday = now.subtract(Duration(days: 30));
    // var newDate = new DateTime(now.year, now.month, now.day - 29);
    monthlyStepData =
        await health.getTotalStepsInInterval(yesterday, now) ?? 0;

它给了我例外 “在 getTotalStepsInInterval 中捕获异常:PlatformException(错误,必须指定有效的最短持续时间:-2134967296,null,java.lang.IllegalArgumentException:必须指定有效的最短持续时间:-2134967296”

如何获取每月步数数据

flutter dart date google-fit applehealth
2个回答
0
投票

要获取每月的步数数据,我们需要使用health包的getHealthDataFromTypes函数。从结果中我们可以仅过滤步骤数据,删除重复项并添加所有值


0
投票

我也面临着同样的问题。通过点击和试用方法,我发现它在 Android 的情况下可以正确返回长达 25 天的数据。我使用以下代码获得了所需的结果:

Future<int> _fetchStepsData(DateTime start, DateTime end) async {
    bool stepsPermission =
        await health.hasPermissions([HealthDataType.STEPS]) ?? false;
    if (!stepsPermission) {
      stepsPermission =
          await health.requestAuthorization([HealthDataType.STEPS]);
    }

    if (stepsPermission) {
      int? steps;
      try {
        steps = await health.getTotalStepsInInterval(start, end);
        return steps ?? 0; // Return the fetched steps count
      } catch (error) {
        print("Caught exception in getTotalStepsInInterval:");
        steps = await fetchStepsDataInChunks(start, end);
        return steps;
      }
    } else {
      print("Authorization not granted - error in authorization");
      return 0; 
    }
  }
  
 Future<int> fetchStepsDataInChunks(DateTime start, DateTime end) async {
const int maxDurationDays = 25;
int totalSteps = 0;

while (start.isBefore(end)) {
  DateTime chunkEnd = start.add(const Duration(days: maxDurationDays - 1));
  if (chunkEnd.isAfter(end)) {
    chunkEnd = end;
  }
  int stepsCount = await _fetchStepsData(start, chunkEnd);
  totalSteps += stepsCount;

  start = chunkEnd.add(const Duration(days: 1));
}

return totalSteps;
}

在上面的代码中,如果抛出异常,我将以 25 天为单位转换时间段,然后将其相加以获得最终步骤。

© www.soinside.com 2019 - 2024. All rights reserved.