requestPermissionToSendNotifications method

  1. @override
Future<bool> requestPermissionToSendNotifications({
  1. String? channelKey,
  2. List<NotificationPermission> permissions = const [NotificationPermission.Alert, NotificationPermission.Sound, NotificationPermission.Badge, NotificationPermission.Vibration, NotificationPermission.Light],
  3. bool openSettingsWhenDenied = false,
})
override

Requests permission from the user to send notifications from the app.

The optional channelKey parameter is a String that represents the key of the notification channel for which to request permission. If this parameter is omitted, the permission will be set for all channels.

The optional permissions parameter is a list of NotificationPermission values that the app requests permission to use. This parameter is optional and defaults to a list of permissions that are commonly requested by apps, including NotificationPermission.Alert, NotificationPermission.Sound, NotificationPermission.Badge, NotificationPermission.Vibration, and NotificationPermission.Light.

Some permissions may require explicit authorization from the user, such as the NotificationPermission.Sound permission on iOS. Other permissions may be granted automatically without user intervention. If a permission requires explicit authorization, this method shows the system's permission dialog without leaving the app. When the user has already denied it and the dialog is no longer available, the method answers false at once, unless openSettingsWhenDenied is true: then the user is taken to the app's notification settings to grant it there.

This method returns a Future that resolves to a bool value indicating whether the permission was granted or not. If the user grants the permission, the value will be true. If the user denies the permission the value will be false.

When the user is taken to the settings, the future waits until the user returns to the app. To open them yourself, use showNotificationConfigPage.

Implementation

@override
Future<bool> requestPermissionToSendNotifications(
    {String? channelKey,
    List<NotificationPermission> permissions = const [
      NotificationPermission.Alert,
      NotificationPermission.Sound,
      NotificationPermission.Badge,
      NotificationPermission.Vibration,
      NotificationPermission.Light
    ],
    bool openSettingsWhenDenied = false}) async {
  final List<String> permissionList = [];
  for (final permission in permissions) {
    String? permissionValue =
        AwesomeAssertUtils.toSimpleEnumString(permission);
    if (permissionValue != null) permissionList.add(permissionValue);
  }

  final List<Object?>? missingPermissions = await methodChannel.invokeMethod(
      CHANNEL_METHOD_REQUEST_NOTIFICATIONS, {
    NOTIFICATION_CHANNEL_KEY: channelKey,
    NOTIFICATION_PERMISSIONS: permissionList,
    NOTIFICATION_OPEN_SETTINGS_WHEN_DENIED: openSettingsWhenDenied,
  });

  return missingPermissions?.isEmpty ?? false;
}