Check OS permission and reveal child toggles in notification settings

This commit is contained in:
zjs81 committed 2026-11-21 20:23:00 -07:00
1 parent 9ac915bdf2
commit eafc4f1152
6 files changed
+1024 -184

No files matched your search

+204 -152
View File
@@ -63,9 +63,9 @@ class AppSettingsScreen extends StatelessWidget {
// NOTIFICATIONS
SectionHeader(context.l10n.appSettings_notifications),
MeshCard(
const MeshCard(
padding: EdgeInsets.zero,
child: _settingsCard(_buildNotificationsContent),
child: NotificationsSettingsSection(),
),
// MESSAGING
@@ -266,156 +266,6 @@ class AppSettingsScreen extends StatelessWidget {
);
}
Widget _buildNotificationsContent(
BuildContext context,
AppSettingsService settingsService,
) {
final notifEnabled = settingsService.settings.notificationsEnabled;
return Column(
children: [
SwitchListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 4,
),
secondary: const Icon(Icons.notifications_outlined, size: 24),
title: Text(context.l10n.appSettings_enableNotifications),
subtitle: Text(context.l10n.appSettings_enableNotificationsSubtitle),
value: settingsService.settings.notificationsEnabled,
onChanged: (value) async {
if (value) {
final granted = await NotificationService().requestPermissions();
if (!granted) {
if (context.mounted) {
showDismissibleSnackBar(
context,
content: Text(
context.l10n.appSettings_notificationPermissionDenied,
),
duration: const Duration(seconds: 2),
);
}
return;
}
}
await settingsService.setNotificationsEnabled(value);
if (context.mounted) {
showDismissibleSnackBar(
context,
content: Text(
value
? context.l10n.appSettings_notificationsEnabled
: context.l10n.appSettings_notificationsDisabled,
),
duration: const Duration(seconds: 2),
);
}
},
),
const Divider(height: 1, indent: 16),
SwitchListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 4,
),
secondary: Icon(
Icons.message_outlined,
size: 24,
color: notifEnabled ? null : Theme.of(context).disabledColor,
),
title: Text(
context.l10n.appSettings_messageNotifications,
style: TextStyle(
color: notifEnabled ? null : Theme.of(context).disabledColor,
),
),
subtitle: Text(
context.l10n.appSettings_messageNotificationsSubtitle,
style: TextStyle(
color: notifEnabled ? null : Theme.of(context).disabledColor,
),
),
value: settingsService.settings.notifyOnNewMessage,
onChanged: notifEnabled
? (value) => settingsService.setNotifyOnNewMessage(value)
: null,
),
if (PlatformInfo.isAndroid) ...[
const Divider(height: 1, indent: 16),
ListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 4,
),
leading: const Icon(Icons.battery_saver_outlined, size: 24),
title: Text(context.l10n.appSettings_batteryOptimization),
subtitle: Text(
context.l10n.appSettings_batteryOptimizationSubtitle,
),
trailing: const Icon(Icons.open_in_new, size: 24),
onTap: BackgroundService.openBatteryOptimizationSettings,
),
],
const Divider(height: 1, indent: 16),
SwitchListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 4,
),
secondary: Icon(
Icons.forum_outlined,
size: 24,
color: notifEnabled ? null : Theme.of(context).disabledColor,
),
title: Text(
context.l10n.appSettings_channelMessageNotifications,
style: TextStyle(
color: notifEnabled ? null : Theme.of(context).disabledColor,
),
),
subtitle: Text(
context.l10n.appSettings_channelMessageNotificationsSubtitle,
style: TextStyle(
color: notifEnabled ? null : Theme.of(context).disabledColor,
),
),
value: settingsService.settings.notifyOnNewChannelMessage,
onChanged: notifEnabled
? (value) => settingsService.setNotifyOnNewChannelMessage(value)
: null,
),
const Divider(height: 1, indent: 16),
SwitchListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 4,
),
secondary: Icon(
Icons.cell_tower,
size: 24,
color: notifEnabled ? null : Theme.of(context).disabledColor,
),
title: Text(
context.l10n.appSettings_advertisementNotifications,
style: TextStyle(
color: notifEnabled ? null : Theme.of(context).disabledColor,
),
),
subtitle: Text(
context.l10n.appSettings_advertisementNotificationsSubtitle,
style: TextStyle(
color: notifEnabled ? null : Theme.of(context).disabledColor,
),
),
value: settingsService.settings.notifyOnNewAdvert,
onChanged: notifEnabled
? (value) => settingsService.setNotifyOnNewAdvert(value)
: null,
),
],
);
}
Widget _buildMessagingContent(
BuildContext context,
AppSettingsService settingsService,
@@ -1870,3 +1720,205 @@ class _ScrollIntoViewOnceState extends State<_ScrollIntoViewOnce> {
@override
Widget build(BuildContext context) => widget.child;
}
class NotificationsSettingsSection extends StatefulWidget {
final Future<bool> Function()? hasPermission;
final Future<bool> Function()? requestPermission;
const NotificationsSettingsSection({
super.key,
this.hasPermission,
this.requestPermission,
});
@override
State<NotificationsSettingsSection> createState() =>
_NotificationsSettingsSectionState();
}
class _NotificationsSettingsSectionState
extends State<NotificationsSettingsSection>
with WidgetsBindingObserver {
bool _hasNotificationPermission = false;
bool _permissionCheckComplete = false;
int _permissionCheckGeneration = 0;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_refreshNotificationPermission(inInit: true);
}
@override
void didUpdateWidget(covariant NotificationsSettingsSection oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.hasPermission != oldWidget.hasPermission) {
_refreshNotificationPermission();
}
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
_refreshNotificationPermission();
}
}
Future<bool> _checkPermission() {
final checker = widget.hasPermission;
if (checker != null) return checker();
return NotificationService().hasNotificationPermission();
}
Future<bool> _requestPermission() {
final requester = widget.requestPermission;
if (requester != null) return requester();
return NotificationService().requestPermissions();
}
void _refreshNotificationPermission({bool inInit = false}) {
final generation = ++_permissionCheckGeneration;
var completedSynchronously = false;
var syncResult = false;
var isSyncWindow = true;
_checkPermission().then((granted) {
if (generation != _permissionCheckGeneration) return;
if (isSyncWindow && inInit) {
completedSynchronously = true;
syncResult = granted;
return;
}
if (!mounted) return;
if (_permissionCheckComplete && _hasNotificationPermission == granted) {
return;
}
setState(() {
_hasNotificationPermission = granted;
_permissionCheckComplete = true;
});
});
isSyncWindow = false;
if (completedSynchronously) {
_hasNotificationPermission = syncResult;
_permissionCheckComplete = true;
}
}
@override
Widget build(BuildContext context) {
final settingsService = context.watch<AppSettingsService>();
final settings = settingsService.settings;
final l10n = context.l10n;
final effectiveEnabled =
settings.notificationsEnabled && _hasNotificationPermission;
final permissionDenied =
_permissionCheckComplete && !_hasNotificationPermission;
const tilePadding = EdgeInsets.symmetric(horizontal: 16, vertical: 4);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SwitchListTile(
contentPadding: tilePadding,
secondary: const Icon(Icons.notifications_outlined, size: 24),
title: Text(l10n.appSettings_enableNotifications),
subtitle: Text(
permissionDenied
? l10n.appSettings_notificationPermissionDenied
: l10n.appSettings_enableNotificationsSubtitle,
),
value: effectiveEnabled,
onChanged: (value) async {
_permissionCheckGeneration++;
if (value) {
final granted = await _requestPermission();
if (!granted) {
if (!context.mounted) return;
setState(() {
_hasNotificationPermission = false;
_permissionCheckComplete = true;
});
showDismissibleSnackBar(
context,
content: Text(l10n.appSettings_notificationPermissionDenied),
duration: const Duration(seconds: 2),
);
return;
}
if (context.mounted) {
setState(() {
_hasNotificationPermission = true;
_permissionCheckComplete = true;
});
}
}
await settingsService.setNotificationsEnabled(value);
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(
value
? l10n.appSettings_notificationsEnabled
: l10n.appSettings_notificationsDisabled,
),
duration: const Duration(seconds: 2),
);
},
),
SettingsReveal(
visible: effectiveEnabled,
children: [
SwitchListTile(
contentPadding: tilePadding,
secondary: const Icon(Icons.message_outlined, size: 24),
title: Text(l10n.appSettings_messageNotifications),
subtitle: Text(l10n.appSettings_messageNotificationsSubtitle),
value: settings.notifyOnNewMessage,
onChanged: settingsService.setNotifyOnNewMessage,
),
const Divider(height: 1, indent: 16),
SwitchListTile(
contentPadding: tilePadding,
secondary: const Icon(Icons.forum_outlined, size: 24),
title: Text(l10n.appSettings_channelMessageNotifications),
subtitle: Text(
l10n.appSettings_channelMessageNotificationsSubtitle,
),
value: settings.notifyOnNewChannelMessage,
onChanged: settingsService.setNotifyOnNewChannelMessage,
),
const Divider(height: 1, indent: 16),
SwitchListTile(
contentPadding: tilePadding,
secondary: const Icon(Icons.cell_tower, size: 24),
title: Text(l10n.appSettings_advertisementNotifications),
subtitle: Text(
l10n.appSettings_advertisementNotificationsSubtitle,
),
value: settings.notifyOnNewAdvert,
onChanged: settingsService.setNotifyOnNewAdvert,
),
if (PlatformInfo.isAndroid) ...[
const Divider(height: 1, indent: 16),
ListTile(
contentPadding: tilePadding,
leading: const Icon(Icons.battery_saver_outlined, size: 24),
title: Text(l10n.appSettings_batteryOptimization),
subtitle: Text(l10n.appSettings_batteryOptimizationSubtitle),
trailing: const Icon(Icons.open_in_new, size: 24),
onTap: BackgroundService.openBatteryOptimizationSettings,
),
],
],
),
],
);
}
}
+117 -27
View File
@@ -180,7 +180,9 @@ class NotificationService {
// connection whose async subscription can throw an unhandled
// SocketException when the bus socket is missing (e.g. running as
// root or inside a container without a session bus).
if (PlatformInfo.isLinux && !_isDbusSessionAvailable()) {
if (PlatformInfo.isLinux &&
defaultTargetPlatform == TargetPlatform.linux &&
!_isDbusSessionAvailable()) {
debugPrint('Skipping notification init: D-Bus session bus unavailable');
return;
}
@@ -250,11 +252,97 @@ class NotificationService {
// Cached "are we allowed to post notifications" result. Null = not yet
// determined. Avoids calling _notifications.show() when it would only throw
// "You must request notifications permissions first" (every web build).
// Android denials are never cached so a later grant in system settings is
// picked up without restarting the app.
// Denials are never cached so a later grant in system settings is picked up
// without restarting the app, and [hasNotificationPermission] refreshes or
// clears [_canNotify] whenever live OS permission is checked.
bool? _canNotify;
static const _permissionRequestedKey = 'notification_permission_requested';
@visibleForTesting
Future<bool> Function()? permissionCheckerForTest;
@visibleForTesting
Future<bool> Function()? permissionRequesterForTest;
@visibleForTesting
Future<bool> ensureCanNotifyForTest() => _ensureCanNotify();
@visibleForTesting
bool? get canNotifyCacheForTest => _canNotify;
@visibleForTesting
void resetForTest() {
_canNotify = null;
_isInitialized = false;
permissionCheckerForTest = null;
permissionRequesterForTest = null;
}
T? _resolvePlugin<T extends FlutterLocalNotificationsPlatform>() {
try {
return _notifications.resolvePlatformSpecificImplementation<T>();
} catch (_) {
return null;
}
}
static bool _isDarwinPermissionGranted(NotificationsEnabledOptions? options) {
if (options == null) return false;
return options.isEnabled ||
options.isProvisionalEnabled ||
options.isAlertEnabled ||
options.isSoundEnabled ||
options.isBadgeEnabled;
}
/// Queries the live OS notification permission state without returning a
/// stale cached grant. Updates [_canNotify] so [_ensureCanNotify] reflects
/// permissions revoked in system settings.
Future<bool> hasNotificationPermission() {
final testChecker = permissionCheckerForTest;
if (testChecker != null) {
return testChecker().then((enabled) {
if (!kIsWeb) {
_canNotify = enabled ? true : null;
}
return enabled;
});
}
if (kIsWeb) return SynchronousFuture<bool>(true);
final androidPlugin =
_resolvePlugin<AndroidFlutterLocalNotificationsPlugin>();
if (androidPlugin != null) {
return androidPlugin.areNotificationsEnabled().then((value) {
final enabled = value ?? false;
_canNotify = enabled ? true : null;
return enabled;
});
}
final iosPlugin = _resolvePlugin<IOSFlutterLocalNotificationsPlugin>();
if (iosPlugin != null) {
return iosPlugin.checkPermissions().then((options) {
final enabled = _isDarwinPermissionGranted(options);
_canNotify = enabled ? true : null;
return enabled;
});
}
final macPlugin = _resolvePlugin<MacOSFlutterLocalNotificationsPlugin>();
if (macPlugin != null) {
return macPlugin.checkPermissions().then((options) {
final enabled = _isDarwinPermissionGranted(options);
_canNotify = enabled ? true : null;
return enabled;
});
}
_canNotify = true;
return SynchronousFuture<bool>(true);
}
Future<bool> _ensureCanNotify() async {
if (!await _ensureInitialized()) return false;
final cached = _canNotify;
@@ -264,50 +352,52 @@ class NotificationService {
// Skip silently instead of logging an error per incoming message.
if (kIsWeb) return _canNotify = false;
// On Android 13+ notifications require an explicit grant; reflect the real
// OS state so we don't spam failed show() calls when denied.
final androidPlugin = _notifications
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>();
if (androidPlugin != null) {
final enabled = await androidPlugin.areNotificationsEnabled() ?? false;
if (enabled) _canNotify = true;
return enabled;
}
// iOS/macOS request permission during initialize(); desktop has no gate.
return _canNotify = true;
return hasNotificationPermission();
}
Future<bool> requestPermissions() async {
final testRequester = permissionRequesterForTest;
if (testRequester != null) {
final granted = await testRequester();
if (!kIsWeb) {
_canNotify = granted ? true : null;
}
return granted;
}
if (!_isInitialized) {
await initialize();
}
// Request Android 13+ notification permission
final androidPlugin = _notifications
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>();
final androidPlugin =
_resolvePlugin<AndroidFlutterLocalNotificationsPlugin>();
if (androidPlugin != null) {
final granted = await androidPlugin.requestNotificationsPermission();
if (granted == true) _canNotify = true;
_canNotify = (granted == true) ? true : null;
return granted ?? false;
}
// iOS permissions are requested during initialization
final iosPlugin = _notifications
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin
>();
final iosPlugin = _resolvePlugin<IOSFlutterLocalNotificationsPlugin>();
if (iosPlugin != null) {
final granted = await iosPlugin.requestPermissions(
alert: true,
badge: true,
sound: true,
);
if (granted == true) _canNotify = true;
_canNotify = (granted == true) ? true : null;
return granted ?? false;
}
final macPlugin = _resolvePlugin<MacOSFlutterLocalNotificationsPlugin>();
if (macPlugin != null) {
final granted = await macPlugin.requestPermissions(
alert: true,
badge: true,
sound: true,
);
_canNotify = (granted == true) ? true : null;
return granted ?? false;
}
+6 -1
View File
@@ -14,7 +14,12 @@ class PlatformInfo {
static bool get isChrome => isWeb && BrowserDetection.isChrome;
/// Whether the app is running on Android.
static bool get isAndroid => !kIsWeb && Platform.isAndroid;
static bool get isAndroid =>
debugIsAndroidOverride ?? (!kIsWeb && Platform.isAndroid);
/// Lets widget tests exercise Android-only UI on a non-Android test host.
@visibleForTesting
static bool? debugIsAndroidOverride;
/// Whether the app is running on iOS.
static bool get isIOS => !kIsWeb && Platform.isIOS;