import 'dart:async'; import 'package:flutter/foundation.dart'; import 'notification_service_bridge.dart'; /// Settings' view of background delivery: the switch, the live status and the /// battery exemption, all read from the native service (never guessed). class NotificationServiceController extends ChangeNotifier { NotificationServiceController( this.bridge, { this.requestNotificationPermission, }) { _changes = bridge.changes.listen(_apply); } final NotificationServiceBridge bridge; /// Asks Android 13+ for POST_NOTIFICATIONS (the app's existing request). final Future Function()? requestNotificationPermission; late final StreamSubscription _changes; NotificationServiceStatus? _status; bool _busy = false; String _error = ''; bool _disposed = false; NotificationServiceStatus? get status => _status; bool get busy => _busy; String get error => _error; Future load() => _run(bridge.status); /// Re-reads after returning from a system screen (permission, battery). Future refresh() => load(); Future setEnabled(bool enabled) => _run(() async { if (enabled && _status?.notificationsAllowed == false) { await requestNotificationPermission?.call(); } return bridge.setEnabled(enabled); }); Future allowNotifications() => _run(() async { await requestNotificationPermission?.call(); return bridge.status(); }); Future allowBackgroundDelivery() => _run(() async { await bridge.requestBatteryExemption(); return bridge.status(); }); Future _run(Future Function() action) async { if (_busy) return; _busy = true; _error = ''; _notify(); try { _status = await action(); } catch (error) { _error = 'Background delivery is unavailable: $error'; } finally { _busy = false; _notify(); } } void _apply(NotificationServiceStatus status) { _status = status; _notify(); } void _notify() { if (!_disposed) notifyListeners(); } @override void dispose() { _disposed = true; unawaited(_changes.cancel()); super.dispose(); } }