New
This commit is contained in:
75
lib/services/health_service.dart
Normal file
75
lib/services/health_service.dart
Normal file
@@ -0,0 +1,75 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:health/health.dart';
|
||||
import 'package:collection/collection.dart';
|
||||
import '../models/cycle_entry.dart';
|
||||
|
||||
class HealthService {
|
||||
static final HealthService _instance = HealthService._internal();
|
||||
factory HealthService() => _instance;
|
||||
HealthService._internal();
|
||||
|
||||
final Health _health = Health();
|
||||
List<HealthDataType> _requestedTypes = [];
|
||||
|
||||
// Define data types for menstruation
|
||||
static const List<HealthDataType> _menstruationDataTypes = [
|
||||
HealthDataType.menstruation,
|
||||
];
|
||||
|
||||
Future<bool> requestAuthorization(List<HealthDataType> types) async {
|
||||
_requestedTypes = types;
|
||||
try {
|
||||
final bool authorized = await _health.requestAuthorization(types);
|
||||
return authorized;
|
||||
} catch (e) {
|
||||
debugPrint("Error requesting authorization: $e");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> hasPermissions(List<HealthDataType> types) async {
|
||||
return await _health.hasPermissions(types);
|
||||
}
|
||||
|
||||
Future<bool> writeMenstruationData(List<CycleEntry> entries) async {
|
||||
// Filter for period days
|
||||
final periodEntries = entries.where((entry) => entry.isPeriodDay).toList();
|
||||
|
||||
if (periodEntries.isEmpty) {
|
||||
debugPrint("No period entries to write.");
|
||||
return true; // Nothing to write is not an error
|
||||
}
|
||||
|
||||
// Check if authorized for menstruation data
|
||||
final hasAuth = await hasPermissions([HealthDataType.menstruation]);
|
||||
if (!hasAuth) {
|
||||
debugPrint("Authorization not granted for menstruation data.");
|
||||
return false;
|
||||
}
|
||||
|
||||
bool allWrittenSuccessfully = true;
|
||||
for (var entry in periodEntries) {
|
||||
try {
|
||||
final success = await _health.writeHealthData(
|
||||
entry.date, // Start date
|
||||
entry.date.add(const Duration(days: 1)), // End date (inclusive of start, so +1 day for all-day event)
|
||||
HealthDataType.menstruation,
|
||||
// HealthKit menstruation type often doesn't need a value,
|
||||
// it's the presence of the event that matters.
|
||||
// For other types, a value would be required.
|
||||
Platform.isIOS ? 0.0 : 0.0, // Value depends on platform and data type
|
||||
);
|
||||
if (!success) {
|
||||
allWrittenSuccessfully = false;
|
||||
debugPrint("Failed to write menstruation data for ${entry.date}");
|
||||
}
|
||||
} catch (e) {
|
||||
allWrittenSuccessfully = false;
|
||||
debugPrint("Error writing menstruation data for ${entry.date}: $e");
|
||||
}
|
||||
}
|
||||
return allWrittenSuccessfully;
|
||||
}
|
||||
|
||||
List<HealthDataType> get mensturationDataTypes => _menstruationDataTypes;
|
||||
}
|
||||
Reference in New Issue
Block a user