Implement husband-wife connection dialogue and theme support for learn articles

This commit is contained in:
2026-01-05 17:09:15 -06:00
parent 02d25d0cc7
commit 96655f9a74
36 changed files with 3849 additions and 819 deletions

View File

@@ -5,20 +5,88 @@ import '../theme/app_theme.dart';
import '../providers/user_provider.dart';
import '../screens/log/pad_tracker_screen.dart';
class PadTrackerCard extends ConsumerWidget {
import 'dart:async';
class PadTrackerCard extends ConsumerStatefulWidget {
const PadTrackerCard({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
ConsumerState<PadTrackerCard> createState() => _PadTrackerCardState();
}
class _PadTrackerCardState extends ConsumerState<PadTrackerCard> {
Timer? _timer;
String _timeDisplay = '';
@override
void initState() {
super.initState();
_startTimer();
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
void _startTimer() {
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
_updateTime();
});
_updateTime();
}
void _updateTime() {
final user = ref.read(userProfileProvider);
if (user?.lastPadChangeTime == null) {
if (mounted) setState(() => _timeDisplay = 'Tap to start');
return;
}
final now = DateTime.now();
final difference = now.difference(user!.lastPadChangeTime!);
// We want to show time SINCE change (duration worn)
final hours = difference.inHours;
final minutes = difference.inMinutes.remainder(60);
final seconds = difference.inSeconds.remainder(60);
String text = '';
if (user.showPadTimerMinutes) {
if (hours > 0) text += '$hours hr ';
text += '$minutes min';
}
if (user.showPadTimerSeconds) {
if (text.isNotEmpty) text += ' ';
text += '$seconds sec';
}
if (text.isEmpty) text = 'Active'; // Fallback
if (mounted) {
setState(() {
_timeDisplay = text;
});
}
}
@override
Widget build(BuildContext context) {
final user = ref.watch(userProfileProvider);
if (user == null || !user.isPadTrackingEnabled) return const SizedBox.shrink();
// Re-check time on rebuilds in case settings changed
// _updateTime(); // Actually let the timer handle it, or use a key to rebuild on setting changes
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const PadTrackerScreen()),
);
).then((_) => _updateTime());
},
child: Container(
padding: const EdgeInsets.all(16),
@@ -58,16 +126,14 @@ class PadTrackerCard extends ConsumerWidget {
),
),
const SizedBox(height: 4),
if (user.lastPadChangeTime != null)
Text(
'Tap to update',
style: GoogleFonts.outfit(fontSize: 12, color: AppColors.warmGray),
)
else
Text(
'Track your change',
style: GoogleFonts.outfit(fontSize: 12, color: AppColors.warmGray),
),
Text(
_timeDisplay.isNotEmpty ? _timeDisplay : 'Tap to track',
style: GoogleFonts.outfit(
fontSize: 14,
fontWeight: FontWeight.w500,
color: AppColors.menstrualPhase
),
),
],
),
),

View File

@@ -0,0 +1,134 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:local_auth/local_auth.dart';
import '../models/user_profile.dart';
class ProtectedContentWrapper extends StatefulWidget {
final Widget child;
final bool isProtected;
final UserProfile? userProfile;
final String title;
const ProtectedContentWrapper({
super.key,
required this.child,
required this.isProtected,
required this.userProfile,
required this.title,
});
@override
State<ProtectedContentWrapper> createState() => _ProtectedContentWrapperState();
}
class _ProtectedContentWrapperState extends State<ProtectedContentWrapper> {
bool _isUnlocked = false;
final LocalAuthentication auth = LocalAuthentication();
Future<void> _authenticate() async {
final user = widget.userProfile;
if (user == null || user.privacyPin == null) {
// Fallback or error if PIN is missing but protected? (Shouldn't happen with UI logic)
return;
}
bool authenticated = false;
// Try Biometrics if enabled
if (user.isBioProtected) {
try {
final bool canCheckBiometrics = await auth.canCheckBiometrics;
if (canCheckBiometrics) {
authenticated = await auth.authenticate(
localizedReason: 'Scan your fingerprint or face to unlock ${widget.title}',
);
}
} on PlatformException catch (e) {
debugPrint('Biometric Error: $e');
// Fallback to PIN
}
}
if (authenticated) {
setState(() {
_isUnlocked = true;
});
return;
}
if (!mounted) return;
// PIN Fallback
final controller = TextEditingController();
final pin = await showDialog<String>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Enter PIN'),
content: TextField(
controller: controller,
keyboardType: TextInputType.number,
obscureText: true,
maxLength: 4,
style: const TextStyle(fontSize: 24, letterSpacing: 8),
textAlign: TextAlign.center,
decoration: const InputDecoration(
hintText: '....',
border: OutlineInputBorder(),
),
autofocus: true,
),
actions: [
TextButton(onPressed: () => Navigator.pop(context), child: const Text('Cancel')),
ElevatedButton(
onPressed: () => Navigator.pop(context, controller.text),
child: const Text('Unlock'),
),
],
),
);
if (pin == user.privacyPin) {
setState(() {
_isUnlocked = true;
});
} else if (pin != null) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Incorrect PIN')),
);
}
}
}
@override
Widget build(BuildContext context) {
// If not protected, or already unlocked, show content
if (!widget.isProtected || _isUnlocked) {
return widget.child;
}
// Otherwise show Lock Screen
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.lock_outline, size: 64, color: Colors.grey),
const SizedBox(height: 16),
Text(
'${widget.title} is Protected',
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 24),
ElevatedButton.icon(
onPressed: _authenticate,
icon: const Icon(Icons.key),
label: Text(widget.userProfile?.isBioProtected == true ? 'Unlock with FaceID / PIN' : 'Enter PIN to Unlock'),
),
],
),
),
);
}
}

View File

@@ -1,54 +1,78 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import '../providers/user_provider.dart';
import '../theme/app_theme.dart';
import '../providers/navigation_provider.dart';
import 'quick_log_dialog.dart';
class QuickLogButtons extends ConsumerWidget {
const QuickLogButtons({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
return Row(
children: [
_buildQuickButton(
context,
icon: Icons.water_drop_outlined,
label: 'Period',
color: AppColors.menstrualPhase,
onTap: () => _navigateToLog(ref),
),
const SizedBox(width: 12),
_buildQuickButton(
context,
icon: Icons.emoji_emotions_outlined,
label: 'Mood',
color: AppColors.softGold,
onTap: () => _navigateToLog(ref),
),
const SizedBox(width: 12),
_buildQuickButton(
context,
icon: Icons.flash_on_outlined,
label: 'Energy',
color: AppColors.follicularPhase,
onTap: () => _navigateToLog(ref),
),
const SizedBox(width: 12),
_buildQuickButton(
context,
icon: Icons.healing_outlined,
label: 'Symptoms',
color: AppColors.lavender,
onTap: () => _navigateToLog(ref),
),
],
final userProfile = ref.watch(userProfileProvider);
final isPadTrackingEnabled = userProfile?.isPadTrackingEnabled ?? false;
return Center(
child: Wrap(
spacing: 12,
runSpacing: 12,
alignment: WrapAlignment.center,
children: [
_buildQuickButton(
context,
icon: Icons.water_drop_outlined,
label: 'Period',
color: AppColors.menstrualPhase,
onTap: () => _showQuickLogDialog(context, 'period'),
),
_buildQuickButton(
context,
icon: Icons.emoji_emotions_outlined,
label: 'Mood',
color: AppColors.softGold,
onTap: () => _showQuickLogDialog(context, 'mood'),
),
_buildQuickButton(
context,
icon: Icons.flash_on_outlined,
label: 'Energy',
color: AppColors.follicularPhase,
onTap: () => _showQuickLogDialog(context, 'energy'),
),
_buildQuickButton(
context,
icon: Icons.healing_outlined,
label: 'Symptoms',
color: AppColors.rose,
onTap: () => _showQuickLogDialog(context, 'symptoms'),
),
_buildQuickButton(
context,
icon: Icons.fastfood_outlined,
label: 'Cravings',
color: AppColors.lavender,
onTap: () => _showQuickLogDialog(context, 'cravings'),
),
if (isPadTrackingEnabled)
_buildQuickButton(
context,
icon: Icons.sanitizer_outlined,
label: 'Pads',
color: AppColors.lutealPhase,
onTap: () => _showQuickLogDialog(context, 'pads'),
),
],
),
);
}
void _navigateToLog(WidgetRef ref) {
// Navigate to the Log tab (index 2)
ref.read(navigationProvider.notifier).setIndex(2);
void _showQuickLogDialog(BuildContext context, String logType) {
showDialog(
context: context,
builder: (context) => QuickLogDialog(logType: logType),
);
}
Widget _buildQuickButton(
@@ -60,7 +84,8 @@ class QuickLogButtons extends ConsumerWidget {
}) {
final isDark = Theme.of(context).brightness == Brightness.dark;
return Expanded(
return Container(
width: 100, // Fixed width for grid item
child: Material(
color: Colors.transparent,
child: InkWell(
@@ -77,12 +102,13 @@ class QuickLogButtons extends ConsumerWidget {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, color: color, size: 24),
const SizedBox(height: 6),
Icon(icon, color: color, size: 28), // Slightly larger icon
const SizedBox(height: 8),
Text(
label,
textAlign: TextAlign.center,
style: GoogleFonts.outfit(
fontSize: 11,
fontSize: 12, // Slightly larger text
fontWeight: FontWeight.w600,
color: isDark ? Colors.white.withOpacity(0.9) : color,
),

View File

@@ -0,0 +1,358 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:uuid/uuid.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/cycle_entry.dart';
import '../providers/user_provider.dart';
import '../providers/navigation_provider.dart';
import '../screens/log/pad_tracker_screen.dart';
import '../theme/app_theme.dart';
class QuickLogDialog extends ConsumerStatefulWidget {
final String logType;
const QuickLogDialog({super.key, required this.logType});
@override
ConsumerState<QuickLogDialog> createState() => _QuickLogDialogState();
}
class _QuickLogDialogState extends ConsumerState<QuickLogDialog> {
// State variables for the dialog
FlowIntensity? _flowIntensity;
MoodLevel? _mood;
int? _energyLevel;
// Symptoms & Cravings
final Map<String, bool> _symptoms = {
'Headache': false,
'Bloating': false,
'Breast Tenderness': false,
'Fatigue': false,
'Acne': false,
'Back Pain': false,
'Constipation': false,
'Diarrhea': false,
'Insomnia': false,
'Cramps': false,
};
final TextEditingController _cravingController = TextEditingController();
List<String> _cravings = [];
List<String> _recentCravings = [];
@override
void initState() {
super.initState();
if (widget.logType == 'cravings') {
_loadRecentCravings();
}
}
@override
void dispose() {
_cravingController.dispose();
super.dispose();
}
Future<void> _loadRecentCravings() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_recentCravings = prefs.getStringList('recent_cravings') ?? [];
});
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text('Quick Log: ${widget.logType.capitalize()}'),
content: _buildLogContent(),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
ElevatedButton(
onPressed: _saveLog,
child: const Text('Save'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop();
ref.read(navigationProvider.notifier).setIndex(2);
},
child: const Text('Full Log'),
)
],
);
}
Widget _buildLogContent() {
switch (widget.logType) {
case 'period':
return _buildPeriodLog();
case 'mood':
return _buildMoodLog();
case 'energy':
return _buildEnergyLog();
case 'pads':
return _buildPadsLog();
case 'symptoms':
return _buildSymptomsLog();
case 'cravings':
return _buildCravingsLog();
default:
return const Text('Invalid log type.');
}
}
Widget _buildSymptomsLog() {
return Container(
width: double.maxFinite,
child: ListView(
shrinkWrap: true,
children: [
const Text('Select symptoms you are experiencing:'),
const SizedBox(height: 16),
Wrap(
spacing: 8,
runSpacing: 8,
children: _symptoms.keys.map((symptom) {
final isSelected = _symptoms[symptom]!;
return ChoiceChip(
label: Text(symptom),
selected: isSelected,
onSelected: (selected) {
setState(() {
_symptoms[symptom] = selected;
});
},
);
}).toList(),
),
],
),
);
}
Widget _buildCravingsLog() {
return Container(
width: double.maxFinite,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
controller: _cravingController,
decoration: const InputDecoration(
labelText: 'Add a craving',
hintText: 'e.g. Chocolate',
border: OutlineInputBorder(),
),
onSubmitted: (value) {
if (value.isNotEmpty) {
setState(() {
_cravings.add(value.trim());
_cravingController.clear();
});
}
},
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
children: _cravings.map((c) => Chip(
label: Text(c),
onDeleted: () {
setState(() => _cravings.remove(c));
},
)).toList(),
),
const SizedBox(height: 16),
if (_recentCravings.isNotEmpty) ...[
Text('Recent Cravings:', style: GoogleFonts.outfit(fontSize: 12, fontWeight: FontWeight.bold)),
const SizedBox(height: 8),
Wrap(
spacing: 8,
children: _recentCravings.take(5).map((c) => ActionChip(
label: Text(c),
onPressed: () {
if (!_cravings.contains(c)) {
setState(() => _cravings.add(c));
}
},
)).toList(),
),
]
],
),
);
}
Widget _buildPeriodLog() {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('Select your flow intensity:'),
const SizedBox(height: 16),
Wrap(
spacing: 8,
children: FlowIntensity.values.map((flow) {
return ChoiceChip(
label: Text(flow.label),
selected: _flowIntensity == flow,
onSelected: (selected) {
if (selected) {
setState(() {
_flowIntensity = flow;
});
}
},
);
}).toList(),
),
],
);
}
Widget _buildMoodLog() {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('Select your mood:'),
const SizedBox(height: 16),
Wrap(
spacing: 8,
children: MoodLevel.values.map((mood) {
return ChoiceChip(
label: Text(mood.label),
selected: _mood == mood,
onSelected: (selected) {
if (selected) {
setState(() {
_mood = mood;
});
}
},
);
}).toList(),
),
],
);
}
Widget _buildEnergyLog() {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('Select your energy level:'),
const SizedBox(height: 16),
Slider(
value: (_energyLevel ?? 3).toDouble(),
min: 1,
max: 5,
divisions: 4,
label: (_energyLevel ?? 3).toString(),
onChanged: (value) {
setState(() {
_energyLevel = value.round();
});
},
),
],
);
}
Widget _buildPadsLog() {
// This can be a simple button to navigate to the PadTrackerScreen
return ElevatedButton(
onPressed: () {
Navigator.of(context).pop();
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => const PadTrackerScreen(),
));
},
child: const Text('Track Pad Change'),
);
}
Future<void> _saveLog() async {
// Handle text input for cravings if user didn't hit enter
if (widget.logType == 'cravings' && _cravingController.text.isNotEmpty) {
_cravings.add(_cravingController.text.trim());
}
final cycleNotifier = ref.read(cycleEntriesProvider.notifier);
final today = DateTime.now();
final entries = ref.read(cycleEntriesProvider);
final entry = entries.firstWhere(
(e) => DateUtils.isSameDay(e.date, today),
orElse: () => CycleEntry(id: const Uuid().v4(), date: today, createdAt: today, updatedAt: today),
);
CycleEntry updatedEntry = entry;
switch (widget.logType) {
case 'period':
updatedEntry = entry.copyWith(
isPeriodDay: true,
flowIntensity: _flowIntensity,
);
break;
case 'mood':
updatedEntry = entry.copyWith(mood: _mood);
break;
case 'energy':
updatedEntry = entry.copyWith(energyLevel: _energyLevel);
break;
case 'symptoms':
updatedEntry = entry.copyWith(
hasHeadache: _symptoms['Headache'],
hasBloating: _symptoms['Bloating'],
hasBreastTenderness: _symptoms['Breast Tenderness'],
hasFatigue: _symptoms['Fatigue'],
hasAcne: _symptoms['Acne'],
hasLowerBackPain: _symptoms['Back Pain'],
hasConstipation: _symptoms['Constipation'],
hasDiarrhea: _symptoms['Diarrhea'],
hasInsomnia: _symptoms['Insomnia'],
crampIntensity: _symptoms['Cramps'] == true ? 2 : 0, // Default to mild cramps if just toggled
);
break;
case 'cravings':
final currentCravings = entry.cravings ?? [];
final newCravings = {...currentCravings, ..._cravings}.toList();
updatedEntry = entry.copyWith(cravings: newCravings);
// Update History
final prefs = await SharedPreferences.getInstance();
final history = prefs.getStringList('recent_cravings') ?? [];
final updatedHistory = {..._cravings, ...history}.take(20).toList();
await prefs.setStringList('recent_cravings', updatedHistory);
break;
default:
// pads handled separately
return;
}
if (entries.any((e) => e.id == entry.id)) {
cycleNotifier.updateEntry(updatedEntry);
} else {
cycleNotifier.addEntry(updatedEntry);
}
if (mounted) {
Navigator.of(context).pop();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Entry saved!')),
);
}
}
}
extension StringExtension on String {
String capitalize() {
return "${this[0].toUpperCase()}${substring(1)}";
}
}