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 _requestedTypes = []; // Define data types for menstruation static const List _menstruationDataTypes = [ HealthDataType.menstruation, ]; Future requestAuthorization(List types) async { _requestedTypes = types; try { final bool authorized = await _health.requestAuthorization(types); return authorized; } catch (e) { debugPrint("Error requesting authorization: $e"); return false; } } Future hasPermissions(List types) async { return await _health.hasPermissions(types); } Future writeMenstruationData(List 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 get mensturationDataTypes => _menstruationDataTypes; }