feat adds proper syncing feature

Signed-off-by: Menno van Leeuwen <menno@vleeuwen.me>
This commit is contained in:
2025-08-27 20:51:29 +02:00
parent b0d5130cbf
commit 2017fd097d
22 changed files with 1518 additions and 3258 deletions

View File

@@ -3,7 +3,6 @@ import 'package:provider/provider.dart';
import '../models/supplement.dart';
import '../providers/supplement_provider.dart';
import '../providers/sync_provider.dart';
class ArchivedSupplementsScreen extends StatefulWidget {
const ArchivedSupplementsScreen({super.key});
@@ -27,35 +26,9 @@ class _ArchivedSupplementsScreenState extends State<ArchivedSupplementsScreen> {
appBar: AppBar(
title: const Text('Archived Supplements'),
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
actions: [
Consumer<SyncProvider>(
builder: (context, syncProvider, child) {
if (!syncProvider.isConfigured) {
return const SizedBox.shrink();
}
return IconButton(
icon: syncProvider.isSyncing
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: syncProvider.status.name == 'success' &&
DateTime.now().difference(syncProvider.lastSyncTime ?? DateTime.now()).inSeconds < 5
? const Icon(Icons.check, color: Colors.green)
: const Icon(Icons.sync),
onPressed: syncProvider.isSyncing ? null : () {
syncProvider.performManualSync();
},
tooltip: syncProvider.isSyncing ? 'Syncing...' : 'Force Sync',
);
},
),
],
),
body: Consumer2<SupplementProvider, SyncProvider>(
builder: (context, provider, syncProvider, child) {
body: Consumer<SupplementProvider>(
builder: (context, provider, child) {
if (provider.archivedSupplements.isEmpty) {
return Center(
child: Column(

View File

@@ -3,7 +3,6 @@ import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import '../providers/supplement_provider.dart';
import '../providers/sync_provider.dart';
class HistoryScreen extends StatefulWidget {
const HistoryScreen({super.key});
@@ -32,32 +31,6 @@ class _HistoryScreenState extends State<HistoryScreen> {
appBar: AppBar(
title: const Text('Intake History'),
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
actions: [
Consumer<SyncProvider>(
builder: (context, syncProvider, child) {
if (!syncProvider.isConfigured) {
return const SizedBox.shrink();
}
return IconButton(
icon: syncProvider.isSyncing
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: syncProvider.status.name == 'success' &&
DateTime.now().difference(syncProvider.lastSyncTime ?? DateTime.now()).inSeconds < 5
? const Icon(Icons.check, color: Colors.green)
: const Icon(Icons.sync),
onPressed: syncProvider.isSyncing ? null : () {
syncProvider.performManualSync();
},
tooltip: syncProvider.isSyncing ? 'Syncing...' : 'Force Sync',
);
},
),
],
),
body: _buildCalendarView(),
);

View File

@@ -51,20 +51,20 @@ class _HomeScreenState extends State<HomeScreen> {
if (!mounted) return;
try {
print('📱 === HOME SCREEN: Checking persistent reminders ===');
print('SupplementsLog: 📱 === HOME SCREEN: Checking persistent reminders ===');
final supplementProvider = context.read<SupplementProvider>();
final settingsProvider = context.read<SettingsProvider>();
print('📱 Settings: persistent=${settingsProvider.persistentReminders}, interval=${settingsProvider.reminderRetryInterval}, max=${settingsProvider.maxRetryAttempts}');
print('SupplementsLog: 📱 Settings: persistent=${settingsProvider.persistentReminders}, interval=${settingsProvider.reminderRetryInterval}, max=${settingsProvider.maxRetryAttempts}');
await supplementProvider.checkPersistentRemindersWithSettings(
persistentReminders: settingsProvider.persistentReminders,
reminderRetryInterval: settingsProvider.reminderRetryInterval,
maxRetryAttempts: settingsProvider.maxRetryAttempts,
);
print('📱 === HOME SCREEN: Persistent reminder check complete ===');
print('SupplementsLog: 📱 === HOME SCREEN: Persistent reminder check complete ===');
} catch (e) {
print('Error checking persistent reminders: $e');
print('SupplementsLog: Error checking persistent reminders: $e');
}
}

View File

@@ -132,7 +132,7 @@ class _PendingNotificationsScreenState extends State<PendingNotificationsScreen>
_isLoading = false;
});
} catch (e) {
print('Error loading notifications: $e');
print('SupplementsLog: Error loading notifications: $e');
setState(() {
_isLoading = false;
});

View File

@@ -5,7 +5,7 @@ import '../providers/settings_provider.dart';
import '../providers/supplement_provider.dart';
import '../services/notification_service.dart';
import 'pending_notifications_screen.dart';
import 'sync_settings_screen.dart';
import 'simple_sync_settings_screen.dart';
class SettingsScreen extends StatelessWidget {
const SettingsScreen({super.key});
@@ -21,6 +21,22 @@ class SettingsScreen extends StatelessWidget {
return ListView(
padding: const EdgeInsets.all(16.0),
children: [
Card(
child: ListTile(
leading: const Icon(Icons.cloud_sync),
title: const Text('Cloud Sync'),
subtitle: const Text('Configure WebDAV sync settings'),
trailing: const Icon(Icons.chevron_right),
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const SimpleSyncSettingsScreen(),
),
);
},
),
),
const SizedBox(height: 16),
Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
@@ -71,18 +87,98 @@ class SettingsScreen extends StatelessWidget {
),
const SizedBox(height: 16),
Card(
child: ListTile(
leading: const Icon(Icons.cloud_sync),
title: const Text('Cloud Sync'),
subtitle: const Text('Configure WebDAV sync settings'),
trailing: const Icon(Icons.chevron_right),
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const SyncSettingsScreen(),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.notifications_active, color: Colors.blue),
const SizedBox(width: 8),
Text(
'Reminders',
style: Theme.of(context).textTheme.titleMedium,
),
],
),
);
},
const SizedBox(height: 8),
Text(
'Configure reminders and how often they are retried when ignored',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 16),
SwitchListTile(
title: const Text('Enable Persistent Reminders'),
subtitle: const Text('Resend notifications if ignored after a specific time'),
value: settingsProvider.persistentReminders,
onChanged: (value) {
settingsProvider.setPersistentReminders(value);
},
),
if (settingsProvider.persistentReminders) ...[
const SizedBox(height: 16),
Text(
'Retry Interval',
style: Theme.of(context).textTheme.titleSmall,
),
const SizedBox(height: 8),
SegmentedButton<int>(
segments: const [
ButtonSegment(value: 5, label: Text('5 min')),
ButtonSegment(value: 10, label: Text('10 min')),
ButtonSegment(value: 15, label: Text('15 min')),
ButtonSegment(value: 30, label: Text('30 min')),
],
selected: {settingsProvider.reminderRetryInterval},
onSelectionChanged: (values) {
settingsProvider.setReminderRetryInterval(values.first);
},
),
const SizedBox(height: 16),
Text(
'Maximum Retry Attempts',
style: Theme.of(context).textTheme.titleSmall,
),
const SizedBox(height: 8),
SegmentedButton<int>(
segments: const [
ButtonSegment(value: 1, label: Text('1')),
ButtonSegment(value: 2, label: Text('2')),
ButtonSegment(value: 3, label: Text('3')),
ButtonSegment(value: 4, label: Text('4')),
ButtonSegment(value: 5, label: Text('5')),
],
selected: {settingsProvider.maxRetryAttempts},
onSelectionChanged: (values) {
settingsProvider.setMaxRetryAttempts(values.first);
},
),
const SizedBox(height: 16),
Text(
'Notification Actions',
style: Theme.of(context).textTheme.titleSmall,
),
const SizedBox(height: 8),
SizedBox(
width: 320,
child: ElevatedButton.icon(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const PendingNotificationsScreen(),
),
);
},
icon: const Icon(Icons.list),
label: const Text('View Pending Notifications'),
),
),
],
],
),
),
),
const SizedBox(height: 16),
@@ -155,354 +251,6 @@ class SettingsScreen extends StatelessWidget {
),
),
),
const SizedBox(height: 16),
Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.notifications_active, color: Colors.blue),
const SizedBox(width: 8),
Text(
'Persistent Reminders',
style: Theme.of(context).textTheme.titleMedium,
),
],
),
const SizedBox(height: 8),
Text(
'Configure automatic reminder retries for ignored notifications',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 16),
SwitchListTile(
title: const Text('Enable Persistent Reminders'),
subtitle: const Text('Resend notifications if ignored'),
value: settingsProvider.persistentReminders,
onChanged: (value) {
settingsProvider.setPersistentReminders(value);
},
),
if (settingsProvider.persistentReminders) ...[
const SizedBox(height: 16),
Text(
'Retry Interval',
style: Theme.of(context).textTheme.titleSmall,
),
const SizedBox(height: 8),
SegmentedButton<int>(
segments: const [
ButtonSegment(value: 5, label: Text('5 min')),
ButtonSegment(value: 10, label: Text('10 min')),
ButtonSegment(value: 15, label: Text('15 min')),
ButtonSegment(value: 30, label: Text('30 min')),
],
selected: {settingsProvider.reminderRetryInterval},
onSelectionChanged: (values) {
settingsProvider.setReminderRetryInterval(values.first);
},
),
const SizedBox(height: 16),
Text(
'Maximum Retry Attempts',
style: Theme.of(context).textTheme.titleSmall,
),
const SizedBox(height: 8),
SegmentedButton<int>(
segments: const [
ButtonSegment(value: 1, label: Text('1')),
ButtonSegment(value: 2, label: Text('2')),
ButtonSegment(value: 3, label: Text('3')),
ButtonSegment(value: 4, label: Text('4')),
ButtonSegment(value: 5, label: Text('5')),
],
selected: {settingsProvider.maxRetryAttempts},
onSelectionChanged: (values) {
settingsProvider.setMaxRetryAttempts(values.first);
},
),
],
],
),
),
),
const SizedBox(height: 16),
Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.notifications_outlined),
const SizedBox(width: 8),
Text(
'Notifications',
style: Theme.of(context).textTheme.titleMedium,
),
],
),
const SizedBox(height: 8),
Text(
'View and manage pending notifications',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const PendingNotificationsScreen(),
),
);
},
icon: const Icon(Icons.list),
label: const Text('View Pending Notifications'),
),
),
],
),
),
),
const SizedBox(height: 16),
if (Theme.of(context).brightness == Brightness.dark) // Only show in debug mode for now
Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.bug_report, color: Colors.orange),
const SizedBox(width: 8),
Text(
'Debug - Notifications',
style: Theme.of(context).textTheme.titleMedium,
),
],
),
const SizedBox(height: 16),
Consumer<SupplementProvider>(
builder: (context, supplementProvider, child) {
return Column(
children: [
ElevatedButton.icon(
onPressed: () async {
await supplementProvider.testNotifications();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Test notification sent!')),
);
}
},
icon: const Icon(Icons.notifications_active),
label: const Text('Test Instant'),
),
const SizedBox(height: 8),
ElevatedButton.icon(
onPressed: () async {
await supplementProvider.testScheduledNotification();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Scheduled test notification for 1 minute from now!')),
);
}
},
icon: const Icon(Icons.schedule),
label: const Text('Test Scheduled (1min)'),
),
const SizedBox(height: 8),
ElevatedButton.icon(
onPressed: () async {
await supplementProvider.testNotificationActions();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Test notification with actions sent! Try the Take/Snooze buttons.')),
);
}
},
icon: const Icon(Icons.touch_app),
label: const Text('Test Actions'),
),
const SizedBox(height: 8),
ElevatedButton.icon(
onPressed: () async {
await NotificationService().testBasicNotification();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Basic test notification sent! Tap it to test callback.')),
);
}
},
icon: const Icon(Icons.tap_and_play),
label: const Text('Test Basic Tap'),
),
const SizedBox(height: 8),
ElevatedButton.icon(
onPressed: () async {
await supplementProvider.rescheduleAllNotifications();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('All notifications rescheduled!')),
);
}
},
icon: const Icon(Icons.refresh),
label: const Text('Reschedule All'),
),
const SizedBox(height: 8),
ElevatedButton.icon(
onPressed: () async {
await supplementProvider.cancelAllNotifications();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('All notifications cancelled!')),
);
}
},
icon: const Icon(Icons.cancel),
label: const Text('Cancel All'),
),
const SizedBox(height: 8),
ElevatedButton.icon(
onPressed: () async {
final pending = await supplementProvider.getPendingNotifications();
if (context.mounted) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Pending Notifications'),
content: pending.isEmpty
? const Text('No pending notifications')
: SizedBox(
width: double.maxFinite,
child: Consumer<SupplementProvider>(
builder: (context, provider, child) {
return ListView.builder(
shrinkWrap: true,
itemCount: pending.length,
itemBuilder: (context, index) {
final notification = pending[index];
// Calculate scheduled time inline
String scheduledTime = '';
try {
final notificationId = notification.id;
if (notificationId == 99999) {
scheduledTime = 'Test notification';
} else if (notificationId > 1000) {
final snoozeMinutes = notificationId % 1000;
scheduledTime = 'Snoozed ($snoozeMinutes min)';
} else {
final supplementId = notificationId ~/ 100;
final reminderIndex = notificationId % 100;
final supplement = provider.supplements.firstWhere(
(s) => s.id == supplementId,
orElse: () => provider.supplements.first,
);
if (reminderIndex < supplement.reminderTimes.length) {
final reminderTime = supplement.reminderTimes[reminderIndex];
final now = DateTime.now();
final timeParts = reminderTime.split(':');
final hour = int.parse(timeParts[0]);
final minute = int.parse(timeParts[1]);
final today = DateTime(now.year, now.month, now.day, hour, minute);
final isToday = today.isAfter(now);
scheduledTime = '${isToday ? 'Today' : 'Tomorrow'} at $reminderTime';
} else {
scheduledTime = 'Unknown time';
}
}
} catch (e) {
scheduledTime = 'ID: ${notification.id}';
}
return Card(
margin: const EdgeInsets.symmetric(vertical: 4),
child: ListTile(
leading: CircleAvatar(
backgroundColor: Theme.of(context).colorScheme.primary,
child: Text(
'${index + 1}',
style: TextStyle(
color: Theme.of(context).colorScheme.onPrimary,
fontWeight: FontWeight.bold,
),
),
),
title: Text(
notification.title ?? 'No title',
style: const TextStyle(fontWeight: FontWeight.w600),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('ID: ${notification.id}'),
Text(notification.body ?? 'No body'),
if (scheduledTime.isNotEmpty) ...[
const SizedBox(height: 4),
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primaryContainer,
borderRadius: BorderRadius.circular(12),
),
child: Text(
'$scheduledTime',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: Theme.of(context).colorScheme.onPrimaryContainer,
),
),
),
],
],
),
isThreeLine: true,
),
);
},
);
},
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Close'),
),
],
),
);
}
},
icon: const Icon(Icons.list),
label: const Text('Show Pending'),
),
],
);
},
),
],
),
),
),
],
);
},

View File

@@ -0,0 +1,467 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../services/database_sync_service.dart';
import '../providers/simple_sync_provider.dart';
class SimpleSyncSettingsScreen extends StatefulWidget {
const SimpleSyncSettingsScreen({super.key});
@override
State<SimpleSyncSettingsScreen> createState() => _SimpleSyncSettingsScreenState();
}
class _SimpleSyncSettingsScreenState extends State<SimpleSyncSettingsScreen> {
final _formKey = GlobalKey<FormState>();
final _serverUrlController = TextEditingController();
final _usernameController = TextEditingController();
final _passwordController = TextEditingController();
final _remotePathController = TextEditingController();
String _previewUrl = '';
@override
void initState() {
super.initState();
_serverUrlController.addListener(_updatePreviewUrl);
_usernameController.addListener(_updatePreviewUrl);
_loadSavedConfiguration();
}
void _loadSavedConfiguration() {
WidgetsBinding.instance.addPostFrameCallback((_) {
final syncProvider = context.read<SimpleSyncProvider>();
if (syncProvider.serverUrl != null) {
_serverUrlController.text = _extractHostnameFromUrl(syncProvider.serverUrl!);
}
if (syncProvider.username != null) {
_usernameController.text = syncProvider.username!;
}
if (syncProvider.password != null) {
_passwordController.text = syncProvider.password!;
}
if (syncProvider.remotePath != null) {
_remotePathController.text = syncProvider.remotePath!;
}
_updatePreviewUrl();
});
}
String _extractHostnameFromUrl(String fullUrl) {
try {
final uri = Uri.parse(fullUrl);
return uri.host;
} catch (e) {
return fullUrl; // Return as-is if parsing fails
}
}
void _updatePreviewUrl() {
setState(() {
if (_serverUrlController.text.isNotEmpty && _usernameController.text.isNotEmpty) {
_previewUrl = _constructWebDAVUrl(_serverUrlController.text, _usernameController.text);
} else {
_previewUrl = '';
}
});
}
@override
void dispose() {
_serverUrlController.removeListener(_updatePreviewUrl);
_usernameController.removeListener(_updatePreviewUrl);
_serverUrlController.dispose();
_usernameController.dispose();
_passwordController.dispose();
_remotePathController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Database Sync Settings'),
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
),
body: Consumer<SimpleSyncProvider>(
builder: (context, syncProvider, child) {
return SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildStatusCard(syncProvider),
const SizedBox(height: 20),
_buildConfigurationSection(),
const SizedBox(height: 20),
_buildActionButtons(syncProvider),
],
),
),
);
},
),
);
}
Widget _buildStatusCard(SimpleSyncProvider syncProvider) {
IconData icon;
Color color;
String statusText = syncProvider.getStatusText();
switch (syncProvider.status) {
case SyncStatus.idle:
icon = Icons.sync;
color = Colors.blue;
break;
case SyncStatus.downloading:
case SyncStatus.merging:
case SyncStatus.uploading:
icon = Icons.sync;
color = Colors.orange;
break;
case SyncStatus.completed:
icon = Icons.check_circle;
color = Colors.green;
break;
case SyncStatus.error:
icon = Icons.error;
color = Colors.red;
break;
}
return Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Row(
children: [
Icon(icon, color: color, size: 24),
const SizedBox(width: 12),
Expanded(
child: Text(
statusText,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
color: color,
),
),
),
],
),
if (syncProvider.lastSyncTime != null) ...[
const SizedBox(height: 8),
Text(
'Last sync: ${_formatDateTime(syncProvider.lastSyncTime!)}',
style: Theme.of(context).textTheme.bodySmall,
),
],
if (syncProvider.lastError != null) ...[
const SizedBox(height: 8),
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.red.withOpacity(0.1),
borderRadius: BorderRadius.circular(4),
),
child: Row(
children: [
Expanded(
child: Text(
syncProvider.lastError!,
style: const TextStyle(color: Colors.red),
),
),
IconButton(
icon: const Icon(Icons.close, color: Colors.red),
onPressed: () => syncProvider.clearError(),
),
],
),
),
],
],
),
),
);
}
Widget _buildConfigurationSection() {
return Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'WebDAV Configuration',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 16),
TextFormField(
controller: _serverUrlController,
decoration: const InputDecoration(
labelText: 'Server URL',
hintText: 'your-nextcloud.com',
helperText: 'Enter just the hostname. We\'ll auto-detect the full WebDAV path.',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a server URL';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _usernameController,
decoration: const InputDecoration(
labelText: 'Username',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a username';
}
return null;
},
),
if (_previewUrl.isNotEmpty) ...[
const SizedBox(height: 8),
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest.withOpacity(0.3),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: Theme.of(context).colorScheme.outline.withOpacity(0.5),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'WebDAV URL Preview:',
style: Theme.of(context).textTheme.labelMedium,
),
const SizedBox(height: 4),
SelectableText(
_previewUrl,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
fontFamily: 'monospace',
color: Theme.of(context).colorScheme.primary,
),
),
],
),
),
],
const SizedBox(height: 16),
TextFormField(
controller: _passwordController,
decoration: const InputDecoration(
labelText: 'Password',
border: OutlineInputBorder(),
),
obscureText: true,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a password';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _remotePathController,
decoration: const InputDecoration(
labelText: 'Remote Path (optional)',
hintText: 'Supplements/',
border: OutlineInputBorder(),
),
),
],
),
),
);
}
Widget _buildActionButtons(SimpleSyncProvider syncProvider) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ElevatedButton(
onPressed: syncProvider.isSyncing ? null : _testConnection,
child: const Text('Test Connection'),
),
const SizedBox(height: 12),
ElevatedButton(
onPressed: syncProvider.isSyncing ? null : _configureSync,
child: const Text('Save Configuration'),
),
const SizedBox(height: 12),
ElevatedButton(
onPressed: (!syncProvider.isConfigured || syncProvider.isSyncing)
? null
: _syncDatabase,
style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(context).primaryColor,
foregroundColor: Colors.white,
),
child: syncProvider.isSyncing
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
),
)
: const Text('Sync Database'),
),
],
);
}
Future<void> _testConnection() async {
if (!_formKey.currentState!.validate()) return;
final syncProvider = context.read<SimpleSyncProvider>();
try {
// Construct the full WebDAV URL from the simple hostname
final fullWebDAVUrl = _constructWebDAVUrl(
_serverUrlController.text.trim(),
_usernameController.text.trim(),
);
// Configure temporarily for testing
await syncProvider.configure(
serverUrl: fullWebDAVUrl,
username: _usernameController.text.trim(),
password: _passwordController.text.trim(),
remotePath: _remotePathController.text.trim().isEmpty
? 'Supplements'
: _remotePathController.text.trim(),
);
final success = await syncProvider.testConnection();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(success
? 'Connection successful!'
: 'Connection failed. Check your settings.'),
backgroundColor: success ? Colors.green : Colors.red,
),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Connection test failed: $e'),
backgroundColor: Colors.red,
),
);
}
}
}
Future<void> _configureSync() async {
if (!_formKey.currentState!.validate()) return;
final syncProvider = context.read<SimpleSyncProvider>();
try {
// Construct the full WebDAV URL from the simple hostname
final fullWebDAVUrl = _constructWebDAVUrl(
_serverUrlController.text.trim(),
_usernameController.text.trim(),
);
await syncProvider.configure(
serverUrl: fullWebDAVUrl,
username: _usernameController.text.trim(),
password: _passwordController.text.trim(),
remotePath: _remotePathController.text.trim().isEmpty
? 'Supplements'
: _remotePathController.text.trim(),
);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Configuration saved successfully!'),
backgroundColor: Colors.green,
),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Failed to save configuration: $e'),
backgroundColor: Colors.red,
),
);
}
}
}
Future<void> _syncDatabase() async {
final syncProvider = context.read<SimpleSyncProvider>();
try {
await syncProvider.syncDatabase();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Database sync completed!'),
backgroundColor: Colors.green,
),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Sync failed: $e'),
backgroundColor: Colors.red,
),
);
}
}
}
String _constructWebDAVUrl(String serverUrl, String username) {
// Remove any protocol prefix if present
String cleanUrl = serverUrl.trim();
if (cleanUrl.startsWith('http://')) {
cleanUrl = cleanUrl.substring(7);
} else if (cleanUrl.startsWith('https://')) {
cleanUrl = cleanUrl.substring(8);
}
// Remove trailing slash if present
if (cleanUrl.endsWith('/')) {
cleanUrl = cleanUrl.substring(0, cleanUrl.length - 1);
}
// For Nextcloud instances, construct the standard WebDAV path
// Default to HTTPS for security
return 'https://$cleanUrl/remote.php/dav/files/$username/';
}
String _formatDateTime(DateTime dateTime) {
return '${dateTime.day}/${dateTime.month}/${dateTime.year} ${dateTime.hour}:${dateTime.minute.toString().padLeft(2, '0')}';
}
}

View File

@@ -4,7 +4,8 @@ import 'package:provider/provider.dart';
import '../models/supplement.dart';
import '../providers/settings_provider.dart';
import '../providers/supplement_provider.dart';
import '../providers/sync_provider.dart';
import '../providers/simple_sync_provider.dart';
import '../services/database_sync_service.dart';
import '../widgets/supplement_card.dart';
import 'add_supplement_screen.dart';
import 'archived_supplements_screen.dart';
@@ -19,7 +20,7 @@ class SupplementsListScreen extends StatelessWidget {
title: const Text('My Supplements'),
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
actions: [
Consumer<SyncProvider>(
Consumer<SimpleSyncProvider>(
builder: (context, syncProvider, child) {
if (!syncProvider.isConfigured) {
return const SizedBox.shrink();
@@ -32,12 +33,13 @@ class SupplementsListScreen extends StatelessWidget {
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: syncProvider.status.name == 'success' &&
DateTime.now().difference(syncProvider.lastSyncTime ?? DateTime.now()).inSeconds < 5
: syncProvider.status == SyncStatus.completed &&
syncProvider.lastSyncTime != null &&
DateTime.now().difference(syncProvider.lastSyncTime!).inSeconds < 5
? const Icon(Icons.check, color: Colors.green)
: const Icon(Icons.sync),
onPressed: syncProvider.isSyncing ? null : () {
syncProvider.performManualSync();
syncProvider.syncDatabase();
},
tooltip: syncProvider.isSyncing ? 'Syncing...' : 'Force Sync',
);
@@ -56,8 +58,8 @@ class SupplementsListScreen extends StatelessWidget {
),
],
),
body: Consumer3<SupplementProvider, SettingsProvider, SyncProvider>(
builder: (context, provider, settingsProvider, syncProvider, child) {
body: Consumer2<SupplementProvider, SettingsProvider>(
builder: (context, provider, settingsProvider, child) {
if (provider.isLoading) {
return const Center(child: CircularProgressIndicator());
}

View File

@@ -1,782 +0,0 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/sync_enums.dart';
import '../providers/sync_provider.dart';
/// Screen for configuring WebDAV sync settings
class SyncSettingsScreen extends StatefulWidget {
const SyncSettingsScreen({super.key});
@override
State<SyncSettingsScreen> createState() => _SyncSettingsScreenState();
}
class _SyncSettingsScreenState extends State<SyncSettingsScreen> {
final _formKey = GlobalKey<FormState>();
final _serverUrlController = TextEditingController();
final _usernameController = TextEditingController();
final _passwordController = TextEditingController();
final _deviceNameController = TextEditingController();
final _syncFolderController = TextEditingController();
bool _isPasswordVisible = false;
bool _isTestingConnection = false;
bool _isConfiguring = false;
@override
void initState() {
super.initState();
_loadCurrentSettings();
}
void _loadCurrentSettings() {
final syncProvider = context.read<SyncProvider>();
_serverUrlController.text = syncProvider.serverUrl ?? '';
_usernameController.text = syncProvider.username ?? '';
_syncFolderController.text = syncProvider.syncFolderName ?? 'Supplements';
// Note: We don't load the password for security reasons
}
@override
void dispose() {
_serverUrlController.dispose();
_usernameController.dispose();
_passwordController.dispose();
_deviceNameController.dispose();
_syncFolderController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Cloud Sync Settings'),
actions: [
Consumer<SyncProvider>(
builder: (context, syncProvider, child) {
if (!syncProvider.isConfigured) return const SizedBox.shrink();
return PopupMenuButton<String>(
onSelected: (value) {
switch (value) {
case 'test':
_testConnection();
break;
case 'sync':
_performSync();
break;
case 'clear':
_showClearConfigDialog();
break;
}
},
itemBuilder: (context) => [
const PopupMenuItem(
value: 'test',
child: ListTile(
leading: Icon(Icons.wifi_protected_setup),
title: Text('Test Connection'),
),
),
const PopupMenuItem(
value: 'sync',
child: ListTile(
leading: Icon(Icons.sync),
title: Text('Sync Now'),
),
),
const PopupMenuItem(
value: 'clear',
child: ListTile(
leading: Icon(Icons.clear),
title: Text('Clear Configuration'),
),
),
],
);
},
),
],
),
body: Consumer<SyncProvider>(
builder: (context, syncProvider, child) {
return SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildStatusCard(syncProvider),
const SizedBox(height: 24),
_buildDeviceInfoSection(syncProvider),
const SizedBox(height: 24),
_buildConfigurationSection(syncProvider),
const SizedBox(height: 24),
_buildSyncSettingsSection(syncProvider),
if (syncProvider.hasPendingConflicts) ...[
const SizedBox(height: 24),
_buildConflictsSection(syncProvider),
],
],
),
),
);
},
),
);
}
Widget _buildStatusCard(SyncProvider syncProvider) {
Color statusColor;
IconData statusIcon;
switch (syncProvider.status) {
case SyncOperationStatus.success:
statusColor = Colors.green;
statusIcon = Icons.check_circle;
break;
case SyncOperationStatus.syncing:
statusColor = Colors.blue;
statusIcon = Icons.sync;
break;
case SyncOperationStatus.networkError:
case SyncOperationStatus.authenticationError:
case SyncOperationStatus.serverError:
statusColor = Colors.red;
statusIcon = Icons.error;
break;
case SyncOperationStatus.conflictsDetected:
statusColor = Colors.orange;
statusIcon = Icons.warning;
break;
default:
statusColor = Colors.grey;
statusIcon = Icons.cloud_off;
}
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(statusIcon, color: statusColor, size: 24),
const SizedBox(width: 12),
Expanded(
child: Text(
syncProvider.statusMessage,
style: Theme.of(context).textTheme.titleMedium,
),
),
],
),
if (syncProvider.lastSyncTime != null) ...[
const SizedBox(height: 8),
Text(
'Last sync: ${syncProvider.formattedLastSyncTime}',
style: Theme.of(context).textTheme.bodySmall,
),
],
if (syncProvider.isConfigured && syncProvider.detectedServerType != null) ...[
const SizedBox(height: 8),
Row(
children: [
Icon(Icons.check_circle, size: 16, color: Colors.green),
const SizedBox(width: 4),
Text(
'Detected: ${syncProvider.detectedServerType}',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.green[700],
fontWeight: FontWeight.w500,
),
),
],
),
],
if (syncProvider.hasError) ...[
const SizedBox(height: 8),
Text(
syncProvider.currentError!,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.red,
),
),
],
if (syncProvider.isSyncing) ...[
const SizedBox(height: 12),
LinearProgressIndicator(
value: syncProvider.syncProgress,
),
],
],
),
),
);
}
Widget _buildConfigurationSection(SyncProvider syncProvider) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'WebDAV Configuration',
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 16),
TextFormField(
controller: _serverUrlController,
decoration: const InputDecoration(
labelText: 'Server URL',
hintText: 'cloud.example.com or drive.mydomain.com',
prefixIcon: Icon(Icons.cloud),
helperText: 'Just enter your server domain - we\'ll auto-detect the rest!',
helperMaxLines: 2,
),
validator: (value) {
if (value?.isEmpty ?? true) {
return 'Please enter server URL';
}
return null;
},
),
const SizedBox(height: 8),
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.blue.withOpacity(0.1),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.blue.withOpacity(0.3)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.lightbulb_outline, size: 16, color: Colors.blue[700]),
const SizedBox(width: 8),
Text(
'Smart URL Detection',
style: Theme.of(context).textTheme.titleSmall?.copyWith(
color: Colors.blue[700],
fontWeight: FontWeight.bold,
),
),
],
),
const SizedBox(height: 8),
Text(
'You can enter simple URLs like:',
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 4),
Text(
'• cloud.example.com\n'
'• drive.mydomain.com\n'
'• nextcloud.company.org\n'
'• my-server.duckdns.org:8080',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
fontFamily: 'monospace',
),
),
const SizedBox(height: 8),
Text(
'We\'ll automatically detect if it\'s Nextcloud, ownCloud, or generic WebDAV and build the correct URL for you!',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
fontStyle: FontStyle.italic,
),
),
],
),
),
const SizedBox(height: 16),
TextFormField(
controller: _usernameController,
decoration: const InputDecoration(
labelText: 'Username',
prefixIcon: Icon(Icons.person),
),
validator: (value) {
if (value?.isEmpty ?? true) {
return 'Please enter username';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _passwordController,
obscureText: !_isPasswordVisible,
decoration: InputDecoration(
labelText: 'Password / App Password',
prefixIcon: const Icon(Icons.lock),
suffixIcon: IconButton(
icon: Icon(
_isPasswordVisible ? Icons.visibility : Icons.visibility_off,
),
onPressed: () {
setState(() {
_isPasswordVisible = !_isPasswordVisible;
});
},
),
helperText: 'Use app passwords for better security',
),
validator: (value) {
if (value?.isEmpty ?? true) {
return 'Please enter password';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _syncFolderController,
decoration: const InputDecoration(
labelText: 'Sync Folder Name',
prefixIcon: Icon(Icons.folder),
hintText: 'Supplements',
helperText: 'Folder name on your cloud server for syncing data',
),
validator: (value) {
if (value?.isEmpty ?? true) {
return 'Please enter folder name';
}
if (value!.contains('/') || value.contains('\\')) {
return 'Folder name cannot contain slashes';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _deviceNameController,
decoration: const InputDecoration(
labelText: 'Device Name (Optional)',
prefixIcon: Icon(Icons.phone_android),
hintText: 'My Phone',
),
),
const SizedBox(height: 24),
Row(
children: [
Expanded(
child: ElevatedButton.icon(
onPressed: _isConfiguring || syncProvider.isSyncing
? null
: () => _configureWebDAV(syncProvider),
icon: _isConfiguring
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.save),
label: Text(syncProvider.isConfigured ? 'Update' : 'Configure'),
),
),
if (syncProvider.isConfigured) ...[
const SizedBox(width: 12),
ElevatedButton.icon(
onPressed: _isTestingConnection || syncProvider.isSyncing
? null
: _testConnection,
icon: _isTestingConnection
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.wifi_protected_setup),
label: const Text('Test'),
),
],
],
),
],
),
),
);
}
Widget _buildSyncSettingsSection(SyncProvider syncProvider) {
if (!syncProvider.isConfigured) return const SizedBox.shrink();
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Sync Settings',
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 16),
SwitchListTile(
title: const Text('Auto Sync on Data Changes'),
subtitle: const Text('Automatically sync when you add, modify, or take supplements'),
value: syncProvider.autoSyncOnDataChanges,
onChanged: syncProvider.setAutoSyncOnDataChanges,
),
const SizedBox(height: 8),
ListTile(
title: const Text('Conflict Resolution'),
subtitle: Text(_getConflictStrategyDescription(syncProvider.conflictStrategy)),
trailing: DropdownButton<ConflictResolutionStrategy>(
value: syncProvider.conflictStrategy,
onChanged: (strategy) {
if (strategy != null) {
syncProvider.setConflictResolutionStrategy(strategy);
}
},
items: ConflictResolutionStrategy.values
.map((strategy) => DropdownMenuItem(
value: strategy,
child: Text(_getConflictStrategyName(strategy)),
))
.toList(),
),
),
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: syncProvider.isSyncing ? null : _performSync,
icon: syncProvider.isSyncing
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.sync),
label: const Text('Sync Now'),
),
),
],
),
),
);
}
Widget _buildConflictsSection(SyncProvider syncProvider) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.warning, color: Colors.orange),
const SizedBox(width: 8),
Text(
'Sync Conflicts',
style: Theme.of(context).textTheme.titleMedium,
),
],
),
const SizedBox(height: 16),
Text(
'${syncProvider.pendingConflicts.length} conflicts need your attention',
style: Theme.of(context).textTheme.bodyMedium,
),
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: ElevatedButton(
onPressed: () => _showConflictsDialog(syncProvider),
child: const Text('Review Conflicts'),
),
),
const SizedBox(width: 12),
ElevatedButton(
onPressed: syncProvider.resolveAllConflicts,
child: const Text('Auto Resolve'),
),
],
),
],
),
),
);
}
Widget _buildDeviceInfoSection(SyncProvider syncProvider) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Connection Information',
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 16),
FutureBuilder<Map<String, String?>>(
future: syncProvider.getDeviceInfo(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
final deviceInfo = snapshot.data!;
return Column(
children: [
if (syncProvider.detectedServerType != null)
ListTile(
leading: const Icon(Icons.cloud_done),
title: const Text('Server Type'),
subtitle: Text(syncProvider.detectedServerType!),
),
if (syncProvider.finalWebdavUrl != null)
ListTile(
leading: const Icon(Icons.link),
title: const Text('WebDAV URL'),
subtitle: Text(
syncProvider.finalWebdavUrl!,
style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
),
),
ListTile(
leading: const Icon(Icons.fingerprint),
title: const Text('Device ID'),
subtitle: Text(deviceInfo['deviceId'] ?? 'Unknown'),
),
ListTile(
leading: const Icon(Icons.devices),
title: const Text('Device Name'),
subtitle: Text(deviceInfo['deviceName'] ?? 'Unknown'),
),
],
);
},
),
],
),
),
);
}
String _getConflictStrategyName(ConflictResolutionStrategy strategy) {
switch (strategy) {
case ConflictResolutionStrategy.preferLocal:
return 'Prefer Local';
case ConflictResolutionStrategy.preferRemote:
return 'Prefer Remote';
case ConflictResolutionStrategy.preferNewer:
return 'Prefer Newer';
case ConflictResolutionStrategy.manual:
return 'Manual';
}
}
String _getConflictStrategyDescription(ConflictResolutionStrategy strategy) {
switch (strategy) {
case ConflictResolutionStrategy.preferLocal:
return 'Always keep local changes';
case ConflictResolutionStrategy.preferRemote:
return 'Always keep remote changes';
case ConflictResolutionStrategy.preferNewer:
return 'Keep most recent changes';
case ConflictResolutionStrategy.manual:
return 'Review each conflict manually';
}
}
Future<void> _configureWebDAV(SyncProvider syncProvider) async {
// For updates, allow empty password to keep existing one
if (syncProvider.isConfigured && _passwordController.text.isEmpty) {
// Skip validation for password on updates
if (_serverUrlController.text.trim().isEmpty || _usernameController.text.trim().isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Please fill in server URL and username'),
backgroundColor: Colors.red,
),
);
return;
}
} else if (!_formKey.currentState!.validate()) {
return;
}
setState(() => _isConfiguring = true);
final success = await syncProvider.configure(
serverUrl: _serverUrlController.text.trim(),
username: _usernameController.text.trim(),
password: _passwordController.text.isEmpty ? null : _passwordController.text,
deviceName: _deviceNameController.text.trim().isEmpty
? null
: _deviceNameController.text.trim(),
syncFolderName: _syncFolderController.text.trim().isEmpty
? 'Supplements'
: _syncFolderController.text.trim(),
);
setState(() => _isConfiguring = false);
if (mounted) {
final message = success
? 'WebDAV configured successfully!'
: 'Failed to configure WebDAV';
final detectionInfo = success && syncProvider.detectedServerType != null
? '\nDetected: ${syncProvider.detectedServerType}'
: '';
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('$message$detectionInfo'),
backgroundColor: success ? Colors.green : Colors.red,
duration: Duration(seconds: success ? 4 : 3),
),
);
if (success) {
_passwordController.clear(); // Clear password for security
}
}
}
Future<void> _testConnection() async {
setState(() => _isTestingConnection = true);
final syncProvider = context.read<SyncProvider>();
final success = await syncProvider.testConnection();
setState(() => _isTestingConnection = false);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(success
? 'Connection test successful!'
: 'Connection test failed'),
backgroundColor: success ? Colors.green : Colors.red,
),
);
}
}
Future<void> _performSync() async {
final syncProvider = context.read<SyncProvider>();
final success = await syncProvider.performManualSync();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(success
? 'Sync completed successfully!'
: 'Sync failed'),
backgroundColor: success ? Colors.green : Colors.red,
),
);
}
}
Future<void> _showClearConfigDialog() async {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Clear Configuration'),
content: const Text(
'Are you sure you want to clear the WebDAV configuration? '
'This will disable cloud sync.',
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('Clear'),
),
],
),
);
if (confirmed == true) {
final syncProvider = context.read<SyncProvider>();
await syncProvider.clearConfiguration();
_serverUrlController.clear();
_usernameController.clear();
_passwordController.clear();
_deviceNameController.clear();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Configuration cleared'),
backgroundColor: Colors.orange,
),
);
}
}
}
Future<void> _showConflictsDialog(SyncProvider syncProvider) async {
await showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Sync Conflicts'),
content: SizedBox(
width: double.maxFinite,
height: 300,
child: ListView.builder(
itemCount: syncProvider.pendingConflicts.length,
itemBuilder: (context, index) {
final conflict = syncProvider.pendingConflicts[index];
return Card(
child: ListTile(
title: Text(conflict.type.name),
subtitle: Text(conflict.description),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
TextButton(
onPressed: () {
syncProvider.resolveConflict(
conflict.syncId,
ConflictResolution.useLocal,
);
},
child: const Text('Local'),
),
TextButton(
onPressed: () {
syncProvider.resolveConflict(
conflict.syncId,
ConflictResolution.useRemote,
);
},
child: const Text('Remote'),
),
],
),
),
);
},
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Close'),
),
],
),
);
}
}