fetchTotalStepsFromSystem method
Fetches the total number of steps from the system's health data for the current day.
This method requests authorization to access step data, retrieves all step entries from the start of the current day until now, and calculates the total steps. If the fetched total steps exceed the previously recorded value, it updates the internal step count. If tracking is active, it manages session step counts and persists the session state. Handles any errors by logging them for debugging purposes.
Implementation
Future<void> fetchTotalStepsFromSystem() async {
try {
final types = [HealthDataType.STEPS];
final now = DateTime.now();
final start = DateTime(now.year, now.month, now.day);
bool requested = await _health.requestAuthorization(types);
if (!requested) return;
List<HealthDataPoint> steps = await _health.getHealthDataFromTypes(
startTime: start,
endTime: now,
types: types,
);
int totalSteps = steps.fold(0, (sum, data) {
if (data.value is NumericHealthValue) {
final numericValue = data.value as NumericHealthValue;
return sum + numericValue.numericValue.round();
}
return sum;
});
if (_totalStepsFromSystem < totalSteps) {
_totalStepsFromSystem = totalSteps;
}
if (_isTracking) {
if (_sessionStartTotalSteps == null) {
_sessionStartTotalSteps = _totalStepsFromSystem;
_sessionSteps = 0;
} else if (_lastSavedTotalSteps != null) {
final stepsSinceLast = _totalStepsFromSystem - _lastSavedTotalSteps!;
if (stepsSinceLast > 0) {
_sessionSteps += stepsSinceLast;
}
}
}
_lastSavedTotalSteps = _totalStepsFromSystem;
await _persistSession();
} catch (e) {
debugPrint('Error fetching steps: $e');
}
}