# Magic Notifications documentation > Magic Notifications brings in-app and OneSignal push notifications to a Magic app through one facade, with polling, realtime delivery and preferences. # Installation Add Magic Notifications to a Magic app, register its provider, and wire the platform files a push needs to reach a device. - [Quick Start](#overview) - [Dependency Setup](#pubdev) - [CLI Installation Wizard](#cli-wizard) - [Service Provider Registration](#service-provider) - [Config Factory in main.dart](#main-dart) - [Platform Setup Summary](#platform-setup) - [Related Documentation](#related-documentation) ## Quick Start ```bash flutter pub add magic_notifications dart run magic:dowel plugin:install magic_notifications dart run magic:dowel notifications:install dart run magic:dowel notifications:doctor ``` | Step | What it does | | :--- | :--- | | `plugin:install` | Injects `NotificationServiceProvider` into `lib/config/app.dart` and registers the package's commands with dowel | | `notifications:install` | Writes `lib/config/notifications.dart` and the platform files, then wires the config into `lib/main.dart` | | `notifications:doctor` | Reports what is still missing | > [!NOTE] > The wizard is the recommended path. A manual setup has to repeat every step it performs; use it only when a pipeline needs fully scripted control. ## Dependency Setup ```bash flutter pub add magic_notifications ``` The package builds on `magic`, `magic_socket` (realtime delivery), `dowel` (the CLI), `onesignal_flutter` and `wind_kit`; `pub` resolves all of them. For local development inside a monorepo, point the dependency at the checkout: ```yaml dependencies: magic_notifications: path: ./plugins/magic_notifications ``` ## CLI Installation Wizard Run the wizard from the Flutter project root, after `plugin:install`: ```bash dart run magic:dowel notifications:install ``` It asks for: 1. **OneSignal App ID**: a UUID, from the [OneSignal Dashboard](https://onesignal.com/). The wizard asks again until the format is valid. 2. **Platforms**: it detects the platform directories the project has and asks to confirm each one. 3. **Web options** (only when web is selected): an optional legacy Safari Web ID and the OneSignal notify button. 4. **Soft prompt**: whether `soft_prompt.enabled` is written as `true`. ### Non-Interactive Mode ```bash dart run magic:dowel notifications:install \ --non-interactive \ --app-id 12345678-1234-1234-1234-123456789012 \ --platforms android,ios,web ``` ```bash # Web extras dart run magic:dowel notifications:install \ --non-interactive \ --app-id 12345678-1234-1234-1234-123456789012 \ --platforms web \ --safari-web-id web.onesignal.auto.xxx \ --notify-button ``` ```bash # Disable the soft prompt and overwrite an existing config dart run magic:dowel notifications:install \ --non-interactive \ --app-id 12345678-1234-1234-1234-123456789012 \ --no-soft-prompt \ --force ``` `--app-id` is required in non-interactive mode and an invalid UUID stops the command before anything is written. See the [CLI reference](https://anilcancakir.com/magic/docs/notifications/basics/cli.md#install) for every flag. ### What the CLI Produces | Artifact | Path | | :--- | :--- | | Notification config | `lib/config/notifications.dart` (skipped with a warning when it exists, unless `--force`) | | Android permission | `android/app/src/main/AndroidManifest.xml` (`POST_NOTIFICATIONS`) | | iOS background mode | `ios/Runner/Info.plist` (`UIBackgroundModes` gains `remote-notification`) | | iOS entitlements | `ios/Runner/Runner.entitlements` (`aps-environment` `development`) and `ios/Runner/RunnerRelease.entitlements` (`production`), both created if absent | | iOS build setting | `ios/Runner.xcodeproj/project.pbxproj` (`CODE_SIGN_ENTITLEMENTS` per configuration) | | Web service worker | `web/OneSignalSDKWorker.js` | | Web SDK script | `web/index.html` (injected once) | | Provider injection | `lib/config/app.dart` | | Config factory | `lib/main.dart` (import plus a `configFactories` entry) | > [!TIP] > Run `dart run magic:dowel notifications:doctor` straight after the install to see every artifact it checks. ## Service Provider Registration `plugin:install` has already edited `lib/config/app.dart`. For a manual setup, add the import and the provider entry: ```dart import 'package:magic_notifications/magic_notifications.dart'; Map get appConfig => { 'app': { 'providers': [ // ... other providers (app) => NotificationServiceProvider(app), ], }, }; ``` `NotificationServiceProvider` runs two phases during framework boot: - `register()` binds `NotificationManager` as a singleton under the `'notifications'` key. - `boot()` registers the database channel, loads the persisted push intent, resolves the push driver named by `notifications.push.driver`, registers the push channel and initialises the driver when an App ID is set, then reconciles the device's push identity once. It starts no polling. See [Service Provider](https://anilcancakir.com/magic/docs/notifications/architecture/service-provider.md) for the full boot sequence. ## Config Factory in main.dart The notification config reaches `Magic.init` as a config factory: ```dart import 'package:flutter/widgets.dart'; import 'package:magic/magic.dart'; import 'config/app.dart'; // The host's own config: declares `appConfig`. import 'config/notifications.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Magic.init( configFactories: [ () => appConfig, () => notificationConfig, // added by notifications:install ], ); runApp(const MyApp()); // `MyApp` is the host's own root widget. } ``` The `notificationConfig` getter lives in `lib/config/notifications.dart`, written by `notifications:install` or `notifications:publish`. Its core shape: ```dart Map get notificationConfig => { 'notifications': { 'push': { 'driver': 'onesignal', 'app_id': '12345678-1234-1234-1234-123456789012', 'service_worker_path': 'OneSignalSDKWorker.js', 'service_worker_scope': '/onesignal/', 'notify_button_enabled': false, }, 'database': { 'enabled': true, 'polling_interval': 30, }, 'soft_prompt': { 'enabled': true, }, }, }; ``` The generated file carries more keys than this and comments on each; [Configuration](https://anilcancakir.com/magic/docs/notifications/getting-started/configuration.md) documents all of them. To keep the App ID out of source control, read it with `env('ONESIGNAL_APP_ID')` instead of a literal, as described there. ## Platform Setup Summary ### iOS The CLI writes the project-file markers a push needs, without opening Xcode: `UIBackgroundModes` gains `remote-notification` in `Info.plist`, `aps-environment` is declared in both entitlements files (`development` for Debug and Profile, `production` for Release), and `CODE_SIGN_ENTITLEMENTS` is pointed at the right file per build configuration. Xcode never reads an entitlements file that no build setting names, which is why the doctor checks the setting and not just the file. What stays manual, because it needs an Apple or OneSignal account rather than a project-file edit: 1. Run `cd ios && pod install --repo-update && cd ..`. 2. Create an APNs key in the [Apple Developer Portal](https://developer.apple.com/account/resources/authkeys/list) (a `.p8` file, its Key ID and your Team ID). One key covers Sandbox and Production, it is team-wide, and it downloads exactly once. 3. Upload the `.p8` key to the OneSignal Dashboard (Settings, Platforms, Apple iOS (APNs)) with the Key ID, your Team ID and your bundle identifier. The installer declines to repoint a project that already names a different entitlements file, one whose configurations are none of Debug, Profile or Release, and one whose project file it cannot rewrite. Each case prints what to do by hand; [Shipping push in a release build](https://anilcancakir.com/magic/docs/notifications/basics/shipping-push.md#release-apns-environment) covers them. #### The Notification Service Extension Push works without the next two steps, which is why they need saying: a build with no extension delivers notifications normally and quietly reports no confirmed deliveries, no rich media and no badge counts. `notifications:doctor` warns when either half is missing. Neither can be automated from a pub package, because both add or change an Xcode target: 4. **App Group.** In Xcode, add the App Groups capability to the **Runner** target with a container named `group..onesignal`. 5. **Notification Service Extension.** File, New, Target, Notification Service Extension, named `OneSignalNotificationServiceExtension`. Add the **same** App Group to that new target and follow OneSignal's current [Flutter SDK setup](https://documentation.onesignal.com/docs/flutter-sdk-setup) for the extension's source and deployment target. The two halves fail independently. An extension with no shared App Group still gives rich media but no confirmed delivery, because the container is how the extension hands what it saw back to the app. > [!WARNING] > Test the cold-start path with a **profile or release** build. iOS refuses to launch a debug Flutter build outside the Flutter tooling, and OneSignal documents that on iOS in Debug a force-closed app opened from a notification does not register the click listener at all. A cold tap that appears to do nothing in Debug is usually this, not your wiring. ### Android The CLI injects `POST_NOTIFICATIONS` into `android/app/src/main/AndroidManifest.xml`: ```xml ``` ### Web The CLI writes the service worker and injects the SDK script. Done by hand: **`web/OneSignalSDKWorker.js`**: ```javascript importScripts("https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.sw.js"); ``` **`web/index.html`**, inside ``: ```html ``` > [!NOTE] > The worker file uses `OneSignalSDK.sw.js` and the page uses `OneSignalSDK.page.js`: they are different build targets. Do not call `OneSignal.init()` in `index.html`; the Dart driver initialises the SDK from `lib/config/notifications.dart`. > [!IMPORTANT] > **iOS Safari only receives web push after the site is added to the Home Screen.** Per [OneSignal's documentation](https://documentation.onesignal.com/docs/en/web-push-for-ios), this "will work on iOS devices only after users add your site to their home screen and open it from there. This is Apple's design requirement." There is no workaround for a plain Safari tab; the app has to tell the person to add the site to their Home Screen first. ## Related Documentation - [Configuration](https://anilcancakir.com/magic/docs/notifications/getting-started/configuration.md): every `notifications.*` key. - [CLI Reference](https://anilcancakir.com/magic/docs/notifications/basics/cli.md): the full command and flag list. - [Shipping push in a release build](https://anilcancakir.com/magic/docs/notifications/basics/shipping-push.md): the differences a development build hides. - [Service Provider](https://anilcancakir.com/magic/docs/notifications/architecture/service-provider.md): what `boot()` does. - [Channels](https://anilcancakir.com/magic/docs/notifications/basics/channels.md) and [Drivers](https://anilcancakir.com/magic/docs/notifications/basics/drivers.md): sending and the push SDK layer. - [Laravel Backend Setup](https://anilcancakir.com/magic/docs/notifications/basics/laravel-backend-setup.md): the API this package talks to. - [Magic installation](https://anilcancakir.com/magic/docs/getting-started/installation): the framework this plugin extends. - [Realtime delivery with magic_socket](https://anilcancakir.com/magic/docs/socket/getting-started/installation): the socket layer behind `Notify.startRealtime`. --- # Configuration Every `notifications.*` config key the package reads, what each one defaults to, and the behaviour behind it. - [Overview](#overview) - [Full Config Map Reference](#config-map) - [notifications.push](#push) - [Asking for permission](#permission) - [Describing the user](#attributes) - [notifications.database](#database) - [notifications.soft_prompt](#soft-prompt) - [Environment Variables](#env) - [Runtime Config Access](#runtime) - [Related Documentation](#related-documentation) ## Overview All configuration lives in one Dart map returned by `notificationConfig`, by default in `lib/config/notifications.dart`. Magic's config repository merges it at boot, so `Config.get(key)` resolves a value anywhere in the app. > [!NOTE] > Create the file with `dart run magic:dowel notifications:publish` or `dart run magic:dowel notifications:install` rather than by hand: the generated file carries a comment on every key. `notifications:configure` edits individual values later. A file generated by an earlier version also contains a `mail` block. The package has no mail channel and no runtime code reads it; only `notifications:channels` prints its value. Delete it. ## Full Config Map Reference ```dart import 'package:magic/magic.dart'; Map get notificationConfig => { 'notifications': { 'push': { 'driver': 'onesignal', 'app_id': env('ONESIGNAL_APP_ID'), // 'safari_web_id': 'web.onesignal.auto.xxx', // legacy Safari only 'service_worker_path': 'OneSignalSDKWorker.js', 'service_worker_scope': '/onesignal/', 'notify_button_enabled': false, 'self_test_enabled': false, 'auto_request_on_login': false, 'reprompt_after_hours': 0, 'fallback_to_settings': true, 'share_user_attributes': false, }, 'push_state': { 'report_path': null, // e.g. '/devices/push-state' 'release_path': null, // e.g. '/devices/push-state/release' 'external_id_prefix': null, // 'user_' when absent }, 'database': { 'enabled': true, 'polling_interval': 30, }, 'soft_prompt': { 'enabled': true, }, }, }; ``` The `push_state` keys are covered in [Telling your backend whether the device can be paged](https://anilcancakir.com/magic/docs/notifications/basics/shipping-push.md#telling-your-backend-whether-the-device-can-be-paged) and [Laravel Backend Setup](https://anilcancakir.com/magic/docs/notifications/basics/laravel-backend-setup.md#onesignal-push). ## notifications.push Controls the push channel and its driver. | Key | Type | Default | Description | | :--- | :--- | :--- | :--- | | `driver` | `String` | none | Name of the push driver. `'onesignal'` is the only built-in one; an absent key means no push is configured and everything else keeps working. Any other value is logged at error level and push stays off, unless a driver of that name was registered with `Notify.extend`. | | `app_id` | `String` | none | OneSignal App ID (UUID). Push initialises only when it is non-empty. | | `safari_web_id` | `String?` | none | Legacy Safari Web Push ID. Modern Safari subscribes over VAPID and needs none. | | `service_worker_path` | `String?` | none | Web only. Path of the OneSignal service worker. Written as `OneSignalSDKWorker.js` by the installer; an absent key sends nothing, so OneSignal uses its own default. | | `service_worker_scope` | `String?` | none | Web only. Scope OneSignal registers its worker under. Written as `/onesignal/` by the installer. A Flutter web build already owns the root scope with `flutter_service_worker.js`, and whichever registration lands second wins that scope, so OneSignal needs a scope of its own. | | `notify_button_enabled` | `bool` | `false` | Web only. Show the floating OneSignal notify button. | | `auto_request_on_login` | `bool` | `false` | Whether the package may raise the OS permission prompt by itself, once, after an identity is declared with `Notify.initializePush(userId)`. See [Asking for permission](#permission). | | `reprompt_after_hours` | `int` | `0` | Hours before the app's own reminder may return to somebody who turned it down. `0` and an absent key mean never. Read by `NotificationManager.pushPromptAdvice()`. | | `fallback_to_settings` | `bool` | `true` | Mobile only. Whether a denied device keeps a route back: the reminder's open-settings button (`Notify.openPushSettings()`) and the SDK's settings fallback on `requestPermission()`. Inert on web. | | `share_user_attributes` | `bool` | `false` | Whether the email and tags described with `Notify.describePushUserUsing` are sent to OneSignal at all. See [Describing the user](#attributes). | | `self_test_enabled` | `bool` | `false` | Gates `PushChannel`, the client-triggered send that asks the backend to push a test notification to the caller's own devices. While it is off, `PushChannel.isAvailable` is `false` and the manager skips the channel. The backend carries the matching `magic-starter.onesignal.self_test_enabled` switch, also off by default, and answers `501` while it is off: set both or neither. | > [!NOTE] > `NotificationServiceProvider.boot()` reads `notifications.push.driver`. For `'onesignal'` it builds `OneSignalWebDriver` on web and `OneSignalDriver` on iOS and Android, then initialises it with `app_id`, `safari_web_id`, `service_worker_path`, `service_worker_scope` and `notify_button_enabled`. A key that is absent stays out of the map the SDK receives. ## Asking for permission There are two separate cadences here, and conflating them is the mistake this section exists to prevent. **The OS prompt is a one-shot.** Once a person has answered it, no code can raise it again: on the web `Notification.requestPermission()` against a denied origin resolves immediately with `denied` and shows nothing, and iOS and Android never show their system dialog again either. What a request does show there is OneSignal's own English dialog offering the app's settings page, while `fallback_to_settings` is on (the default); with it off, a request on a denied phone shows nothing. The only route back is the browser's site settings or the OS Settings app. So an automatic request is worth exactly one shot, on a device that has never been asked. **The app's own reminder is not a one-shot.** It is your UI, and it may appear on whatever cadence you configure, including on a device whose OS permission is denied: on mobile its button opens the app's own notification settings page directly (see `fallback_to_settings`), which is a real route back. ### The automatic request With `auto_request_on_login: true`, the package raises the platform request once, from `want()` (which `Notify.initializePush(userId)` calls), and only when: - the OS has never asked on this device (`PushDriver.canRaisePermissionRequest()`), - the device is not already subscribed (its reachability is `off`), - and it has not already been raised in this launch. It is never raised from `reconcilePushIdentity()`, which runs on every auth-state change and on a signed-out boot: a dialog from there arrives with nothing in front of it explaining what it is for. > [!WARNING] > On web, browsers require a user gesture for a permission request and a login is not one, so this key can spend the ask without rendering it. Prefer the reminder below, whose button is a tap. ### The reminder, and what its button can do Ask the package rather than deriving it: ```dart import 'package:flutter/widgets.dart'; import 'package:magic_notifications/magic_notifications.dart'; // `MyOwnStorage` and the three `My...Row` widgets are the host app's own. Future pushPromptRow(MyOwnStorage myOwnStorage) async { final advice = await Notify.manager.pushPromptAdvice( declinedAt: await myOwnStorage.readPushPromptDeclinedAt(), ); if (!advice.show) return const SizedBox.shrink(); return switch (advice.action) { // A real dialog will appear: Notify.requestPushPermission(). PushPromptAction.request => MyEnableRow(), // The prompt is spent, but this platform can open the app's own // notification settings page: Notify.openPushSettings(). PushPromptAction.openSettings => MyOpenSettingsRow(), // Nowhere to send the tap. Say where the switch lives instead. PushPromptAction.instructions => MyBlockedInstructionsRow(), PushPromptAction.none => const SizedBox.shrink(), }; } ``` `advice.show` already accounts for `reachability()`, `reprompt_after_hours`, `soft_prompt.enabled` and the timestamp you passed in. `advice.reachability` is the same four-state read, carried so a status row does not need a second platform call. The package ships this row as `PushPromptHost`; see [Push Prompt Component](https://anilcancakir.com/magic/docs/notifications/basics/preferences.md#push-prompt). The decline timestamp stays yours. A decline is your UI's event, recorded wherever you already keep device state; a copy inside this package would be a second answer to drift out of sync with the first. ## Describing the user OneSignal segments and personalises on what it knows about a person: an email subscription, and tags. This package owns the transport and the identity lifecycle; your app owns the values, because "email, first name, last name" is one product's answer and the next app has different fields or is not permitted to send an address at all. Register the description once, at boot, next to wherever you register the driver: ```dart import 'package:magic/magic.dart'; import 'package:magic_notifications/magic_notifications.dart'; // `User` is the host app's own model. void describePushUser() { Notify.describePushUserUsing((String externalId) { final user = Auth.user(); if (user == null) return null; // nothing to describe for this identity return PushUserAttributes( email: user.email, tags: { 'first_name': user.firstName, 'last_name': user.lastName, }, ); }); } ``` `User` is your own model. `externalId` is the string you passed to `Notify.initializePush()`, so an app that keeps its user state elsewhere can look the right person up. The resolver is called on every login and every account switch, so nothing re-registers per login. Returning `null` says there is nothing to describe, which is the answer for a guest or for somebody who has not consented. Nothing is sent until `share_user_attributes` is `true`. An app that registers no description sends nothing either. ### What an account switch does Everything this package wrote is removed **before** the `login` or `logout` that moves the device on, while the SDK still points at the person it was written for. The SDK's own migration guide is the reason (`onesignal_flutter`, `MIGRATION_GUIDE.md`): a `login` to an id that does not exist yet creates the user *and applies the operations already performed under the device-scoped user to it*, and a `logout` leaves exactly such a device-scoped user behind. A removal issued after the switch therefore follows the next person onto their record, and on a shared device that is the whole problem. The cost is that the previous person's tags come off their OneSignal record when they leave this device, and the resolver puts them straight back on their next login anywhere. The alternative is leaving a name and an email address attached to a subscription that has moved to somebody else. Only what this package wrote is ever removed. A tag set from the OneSignal dashboard, from your backend, or from another client is not this device's to delete. ### Two things to get right **A tag written from a client is user-tamperable.** Anybody holding the app can call the SDK from a browser console and write whatever they like under any key. That is fine for choosing an audience and fine for personalising a message. It is not fine for anything a backend later trusts: a plan tier, an entitlement, a role, a quota. Those belong in a server-side tag write over OneSignal's REST API, from the system that already owns the fact. This package ships no such path. **An email address and a name are personal data going to a third party.** That is what `share_user_attributes` gates, and why it ships off. It gates the whole seam rather than the email alone, because this package cannot tell one tag from another: `{'first_name': 'Ada'}` is as personal as an address and `{'plan': 'pro'}` is not, and both arrive here as two strings. ### Platform parity Both OneSignal drivers implement the same four calls (`setTags`, `removeTags`, `addEmail`, `removeEmail`) against the same v16 user model, so a description behaves identically on mobile and on the web. The one difference is a browser's to make: the web SDK is whatever script your `web/index.html` loads, so the driver checks that `User.addEmail` exists before it uses it and reports through the log when it does not, instead of accepting an address that went nowhere. A custom `PushDriver` inherits `removeTags` (a loop over `removeTag`) and an `addEmail` that sends nothing and says so in the log. ## notifications.database Controls polling for in-app notifications. | Key | Type | Default | Description | | :--- | :--- | :--- | :--- | | `enabled` | `bool` | `true` | Written by the installer and shown by `notifications:channels`. The runtime does not read it: `DatabaseChannel` is always registered and always available. | | `polling_interval` | `int` | `30` | Seconds between `GET /notifications` requests. Supported range: 5 to 600. | Change the interval with: ```bash dart run magic:dowel notifications:configure --polling-interval 60 ``` The runtime reads this key when it builds the poller, which is the first `startPolling()` and any `startPolling()` after a `stopPolling()`, including the automatic handoff when a realtime socket drops (that path stops the poller first). A change therefore takes effect on the next start. It does not take effect across `pausePolling()` and `resumePolling()`: those keep the same poller instance, so it keeps the interval it was constructed with. Call `stopPolling()` and then `startPolling()` to apply a new value to a poller that is already running. A value the reader cannot use is logged rather than thrown, because this is a timer wired to your auth state and a mistyped number must not take notification delivery down: | Configured | Used | Why | | :--- | :--- | :--- | | absent | 30 | the default | | below 5, including `0` and negatives | 5 | `Timer.periodic` accepts `0` and then fires on every event-loop turn | | above 600 | 600 | the supported range, enforced | | not an `int` (`'30'`, `30.0`) | 30 | the value is type-checked rather than cast, so it reads as absent | ## notifications.soft_prompt | Key | Type | Default | Description | | :--- | :--- | :--- | :--- | | `enabled` | `bool` | `true` | Whether your own soft prompt should show before `Notify.requestPushPermission()`. `NotificationManager.pushPromptAdvice()` honours it (`false` answers `show: false`), so a call site using that API does not check it a second time. | The installer writes `title` and `message` keys beside `enabled` as copy suggestions for a prompt you build yourself. The package never reads them; `PushPrompt` takes its strings from translation keys (see [Translation Keys](https://anilcancakir.com/magic/docs/notifications/basics/preferences.md#translation-keys)). A call site that needs the raw device state reads `reachability()` on the resolved driver (see [Drivers](https://anilcancakir.com/magic/docs/notifications/basics/drivers.md#abstract)); one deciding whether to interrupt somebody asks `pushPromptAdvice()` instead, which folds this key, the re-prompt interval and the platform's route back into one answer. ```dart import 'package:magic_notifications/magic_notifications.dart'; Future checkReachability() async { final reachability = await Notify.manager.pushDriver.reachability(); if (reachability == PushReachability.blocked) { // The OS will not re-prompt. Point at the platform setting instead. } } ``` ## Environment Variables The installer writes the App ID as a literal. To keep it out of source control, read it from `.env` with Magic's `env` helper: ```dart import 'package:magic/magic.dart'; // In `notificationConfig`, under `notifications.push`. Map pushConfig() { final Map push = { 'app_id': env('ONESIGNAL_APP_ID'), }; return push; } ``` ``` ONESIGNAL_APP_ID=12345678-1234-1234-1234-123456789012 ``` `notifications:doctor` recognises `env('KEY')`, `env('KEY')` and an `envString('KEY', fallback)` wrapper. It cannot read the value a build will see, so it reports the key it comes from, and warns when `.env` is missing or carries nothing for that key. A form it does not recognise, such as `String.fromEnvironment`, reads as an App ID that is not configured. Magic loads `.env` as a Flutter asset; see [Magic configuration](https://anilcancakir.com/magic/docs/getting-started/configuration). ## Runtime Config Access After Magic boots, any value is available through `Config.get`: ```dart import 'package:magic/magic.dart'; ({String? appId, int? interval, bool? softPrompt}) readNotificationConfig() { final appId = Config.get('notifications.push.app_id'); final interval = Config.get('notifications.database.polling_interval'); final softPrompt = Config.get('notifications.soft_prompt.enabled'); return (appId: appId, interval: interval, softPrompt: softPrompt); } ``` `Config.get` returns `null` when the key is absent or has another type; use `??` for a default: ```dart import 'package:magic/magic.dart'; bool selfTestEnabled() { final selfTest = Config.get('notifications.push.self_test_enabled') ?? false; return selfTest; } ``` ## Related Documentation - [Installation](https://anilcancakir.com/magic/docs/notifications/getting-started/installation.md): how the config file gets into the app. - [Service Provider](https://anilcancakir.com/magic/docs/notifications/architecture/service-provider.md): which keys `boot()` reads. - [CLI Reference](https://anilcancakir.com/magic/docs/notifications/basics/cli.md): `configure` and `publish`. - [Preferences](https://anilcancakir.com/magic/docs/notifications/basics/preferences.md): the push prompt component and every translation key the shipped widgets read. - [Shipping push in a release build](https://anilcancakir.com/magic/docs/notifications/basics/shipping-push.md): service worker settings and device reachability reports. --- # Channels How a notification reaches its channels: the `NotificationChannel` contract, the database and push channels the package registers, and how to add your own. - [Channel Concept](#concept) - [NotificationChannel Interface](#interface) - [DatabaseChannel](#database-channel) - [PushChannel](#push-channel) - [Creating Custom Channels](#custom-channels) - [Channel Registration](#registration) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Channel Concept A channel is a delivery mechanism. `NotificationManager.send` asks the notification which channels it wants through `Notification.via()`, then dispatches to each registered channel in turn. ```dart import 'package:magic_notifications/magic_notifications.dart'; class MonitorDownNotification extends Notification { @override List via(Notifiable notifiable) => ['database', 'push']; } Future alert(Notifiable user) async { await Notify.send(user, MonitorDownNotification()); } ``` Channels are identified by a string name. For each name the manager: 1. skips it with a logged warning when no channel is registered under it, 2. skips it when `isAvailable` is `false`, 3. awaits `channel.send(notifiable, notification)`. Channels run one after another. A channel that throws does not stop the rest: the manager finishes the list, logs every later failure, and rethrows the first error once all channels have been tried. Declaring a channel in `via()` is therefore safe without knowing at compile time whether the device supports it. ## NotificationChannel Interface ```dart import 'package:magic_notifications/magic_notifications.dart'; abstract class NotificationChannel { String get name; bool get isAvailable; Future send(Notifiable notifiable, Notification notification); } ``` | Member | Contract | | :--- | :--- | | `name` | The key used in `via()` and by `registerChannel` | | `isAvailable` | A synchronous guard checked before every `send`; `false` skips the channel silently | | `send` | The delivery logic; receives the target entity and the notification | ## DatabaseChannel `NotificationServiceProvider.boot()` registers `DatabaseChannel` whether or not push is configured. It is always available, and its `send` does nothing: ```dart import 'package:magic_notifications/magic_notifications.dart'; class DatabaseChannel extends NotificationChannel { @override String get name => 'database'; @override bool get isAvailable => true; @override Future send(Notifiable notifiable, Notification notification) async { // Returns without doing anything: the backend owns the rows. } } ``` ### How It Works The database channel is asymmetric: 1. **The backend creates**: the Laravel backend calls `$user->notify(new SomeNotification())`, which persists a row in the `notifications` table. 2. **The client reads**: `NotificationPoller` calls `NotificationManager.fetchNotifications()` every 30 seconds by default (`notifications.database.polling_interval`), which hits `GET /notifications`. With a socket, `Notify.startRealtime()` applies each pushed row instead. 3. **A stream emits**: results go to the broadcast stream behind `Notify.notifications()`. 4. **The UI reacts**: any widget listening to that stream receives the updated list. `DatabaseChannel.send` exists for parity with Laravel's `via()` vocabulary. A client-created row is not supported by this channel; post to your backend's own endpoint for that. **`DatabaseNotification` fields:** | Field | Type | Description | | :--- | :--- | :--- | | `id` | `String` | Id from the backend | | `type` | `String` | Notification type (for example `monitor_down`) | | `title` | `String` | Read from `data['title']` | | `body` | `String` | Read from `data['body']` | | `data` | `Map` | The full `data` payload | | `actionUrl` | `String?` | Read from `data['action_url']` | | `createdAt` | `DateTime` | Creation timestamp | | `readAt` | `DateTime?` | `null` while unread | | `isRead` | `bool` | `readAt != null` | ## PushChannel `PushChannel` is registered when a push driver resolves. It is **self-addressed** and ships **switched off**. | Property | Behaviour | | :--- | :--- | | `name` | `'push'` | | `isAvailable` | `driver.isSupported` and `notifications.push.self_test_enabled` is `true`. With the switch off the manager skips the channel, so the other channels in `via()` still deliver. | | Recipient | None. It posts to `POST /notifications/push-test` and the backend derives the recipient from the session, so the only person it can page is the authenticated one. A `Notifiable` whose `notifiableId` is not the signed-in user's id throws `NotificationException` with code `PUSH_RECIPIENT_NOT_AUTHENTICATED_USER`. | | Payload | `title` (`heading`), `body` (`content`) and `data` from `toPush()`; a `url` set on the `PushMessage` is folded into `data['url']` unless `data` already has one. | | Failure | A non-successful response throws `NotificationException` with code `HTTP_`. | Ordinary push to other people is sent by your backend through OneSignal; see [Laravel Backend Setup](https://anilcancakir.com/magic/docs/notifications/basics/laravel-backend-setup.md#onesignal-push). This channel exists so a person can find out whether push reaches their own phone before an incident rather than during one. The backend carries the matching `magic-starter.onesignal.self_test_enabled` switch; enable both or neither. ### How It Works 1. With the switch off, `send` logs a debug line and returns. 2. A foreign recipient is refused with the exception above. 3. `toPush()` is called on the notification; a `null` return exits early. 4. When the `Notifiable` has a `notificationPreference`, `isEnabled(notification.type, 'push')` must be `true` (see [Preferences](https://anilcancakir.com/magic/docs/notifications/basics/preferences.md#global-vs-type)). 5. The request is sent. > [!TIP] > Build the `toPush()` payload with `PushMessage`: > ```dart > import 'package:magic_notifications/magic_notifications.dart'; > > /// The host app's model. > class Monitor { > const Monitor(this.id); > > final int id; > } > > class MonitorDownNotification extends Notification { > MonitorDownNotification(this.monitor); > > final Monitor monitor; > > @override > List via(Notifiable notifiable) => ['push']; > > @override > PushMessage? toPush(Notifiable notifiable) { > return PushMessage() > .heading('Monitor Down') > .content('api.example.com is not responding') > .data({'monitor_id': monitor.id}) > .url('/monitors/${monitor.id}'); > } > } > ``` ## Creating Custom Channels Extend `NotificationChannel` for any other delivery mechanism: ```dart import 'package:magic/magic.dart'; import 'package:magic_notifications/magic_notifications.dart'; class SlackChannel extends NotificationChannel { final String _webhookUrl; SlackChannel(this._webhookUrl); @override String get name => 'slack'; @override bool get isAvailable => _webhookUrl.isNotEmpty; @override Future send(Notifiable notifiable, Notification notification) async { final data = notification.toDatabase(notifiable); if (data == null) return; await Http.post(_webhookUrl, data: { 'text': '${data['title']}: ${data['body']}', }); } } ``` Then name it in `via()`: ```dart import 'package:magic_notifications/magic_notifications.dart'; class DeployFinishedNotification extends Notification { @override List via(Notifiable notifiable) => ['database', 'slack']; // `SlackChannel.send` reads this: the base `toDatabase` returns `null`. @override Map? toDatabase(Notifiable notifiable) => { 'title': 'Deploy finished', 'body': 'The release is live.', }; } ``` ## Channel Registration `NotificationServiceProvider` registers `database` and `push` itself. Register any other channel from the `boot()` of a provider of your own: ```dart import 'package:magic/magic.dart'; import 'package:magic_notifications/magic_notifications.dart'; // The host's own channel from the section above, and its webhook url. const String webhookUrl = 'https://hooks.example.com/slack'; class SlackServiceProvider extends ServiceProvider { SlackServiceProvider(super.app); @override void register() {} @override Future boot() async { NotificationManager().registerChannel(SlackChannel(webhookUrl)); } } ``` Registering a name that already exists replaces the previous instance, which is how a test swaps in a fake. `hasChannel` answers whether a name is registered: ```dart import 'package:magic_notifications/magic_notifications.dart'; bool hasPushChannel() { final bool exists = NotificationManager().hasChannel('push'); return exists; } ``` ## Gotchas | Mistake | Fix | | :--- | :--- | | Expecting `DatabaseChannel.send` to store a row | It does nothing. The backend creates database notifications; the client reads them with `Notify.notifications()` and polling or realtime. | | Listing `'push'` in `via()` and seeing nothing happen | `PushChannel` is unavailable until `notifications.push.self_test_enabled` is `true` and the driver is supported. It only reaches the signed-in user. Send push to other people from your backend. | | Listing `'mail'` in `via()` | The package has no mail channel. The manager logs `Unknown notification channel: mail` and skips it; send mail from the backend. | | Assuming one failing channel blocks the next | It does not. Every channel is tried, then the first error is rethrown from `send`; wrap the call if a failure must not surface. | | `Notification` is ambiguous after importing Flutter | Flutter's widgets library also exports `Notification`. Import it with `hide Notification` (`import 'package:flutter/widgets.dart' hide Notification;`). | ## Related Documentation - [Drivers](https://anilcancakir.com/magic/docs/notifications/basics/drivers.md): the push SDK layer behind `PushChannel`. - [Preferences](https://anilcancakir.com/magic/docs/notifications/basics/preferences.md): the per-type and per-channel opt-outs `PushChannel` honours. - [Notification Manager](https://anilcancakir.com/magic/docs/notifications/architecture/notification-manager.md): dispatch, polling and realtime. - [Laravel Backend Setup](https://anilcancakir.com/magic/docs/notifications/basics/laravel-backend-setup.md): the backend that creates the rows and sends the pushes. - [Realtime channels with magic_socket](https://anilcancakir.com/magic/docs/socket/basics/channels): the socket layer `Notify.startRealtime` subscribes through. --- # Drivers The push driver layer: the `PushDriver` contract, the OneSignal drivers for mobile and web, how the right one is chosen, and how to supply your own. - [Driver Concept](#concept) - [PushDriver Abstract Class](#abstract) - [OneSignalDriver (iOS and Android)](#onesignal-mobile) - [OneSignalWebDriver (Web)](#onesignal-web) - [Conditional Imports via onesignal_factory.dart](#conditional) - [Creating a Custom Driver](#custom) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Driver Concept A push driver wraps a platform push SDK behind one API, so the manager and `PushChannel` never touch SDK internals. The manager resolves the driver lazily from a name-keyed registry (see [Push Driver Setup](https://anilcancakir.com/magic/docs/notifications/architecture/notification-manager.md#push-driver)); `notifications.push.driver` selects the name, and `'onesignal'` is the only driver the package ships. ```dart import 'package:magic_notifications/magic_notifications.dart'; final PushDriver? driver = Notify.manager.pushDriverOrNull; // null when push is not configured ``` ## PushDriver Abstract Class ### Key Members | Member | Description | | :--- | :--- | | `name` | Driver identifier (for example `'onesignal'`) | | `isSupported` | Synchronous platform check; `PushChannel.isAvailable` depends on it | | `isInitialized` | Whether `initialize` brought the SDK up. `true` by default. Both OneSignal drivers answer `false` before `initialize` and after a failed one, and the provider never starts them when `app_id` is blank. | | `permissionState()` | Current `PushPermissionState` (`notDetermined`, `denied`, `authorized`, `provisional`). Mobile reads the native permission; web reads the browser's `Notification.permission`. | | `isOptedIn` | Whether the person is actively subscribed | | `initialize(config)` | One-time SDK initialisation; call it before everything else | | `login(externalId)` / `logout()` | Associate or release the account on the subscription | | `currentExternalId()` | The external id the device is subscribed as, or `null`. It closes the loop on `login` and `logout`: without it nothing can tell whether the SDK acted on the identity it was given. | | `currentSubscriptionId()` | The platform subscription id, or `null`. A push cannot be addressed without one, which is why `reachability()` consults it. | | `requestPermission()` | Raises the OS permission dialog; `true` when granted | | `canRaisePermissionRequest()` | `true` only while the OS has never asked (`permissionState()` is `notDetermined`) | | `canOpenPlatformSettings` / `openPlatformSettings()` | Whether the driver can open the app's own notification settings, and doing so. The base class answers `false` and throws `UnsupportedPlatformException`. | | `optIn()` / `optOut()` | Re-subscribe or unsubscribe without clearing the external id | | `setTags(tags)` / `removeTag(key)` / `removeTags(keys)` | Segmentation tags; `removeTags` defaults to a loop over `removeTag` | | `addEmail(email)` / `removeEmail(email)` | Email subscription on the user. The base class logs that it has no email transport and sends nothing. | | `onNotificationReceived` | Broadcast stream; a push arrived while the app was in the foreground | | `onNotificationClicked` | Broadcast stream; the person tapped a notification | | `onPermissionChanged` | Broadcast stream; the OS permission state moved | | `onIdentityChanged` | Broadcast stream of `PushIdentityChange`; the SDK reports that the user or subscription changed underneath the app. The only trustworthy confirmation that a `login` or `logout` landed. | | `subjectGuard` / `mayDisplay(data)` | Set by the manager. A push that arrives while the app is in the foreground and whose `subject` names somebody other than the signed-in identity is neither drawn nor republished: the drivers apply the guard in their foreground-display listener. In the background or with the app closed that listener does not run and the OS draws the notification with no client code involved, so the guard cannot stop it; only the server can, by no longer addressing a subscription that belongs to a previous person. | | `reachability()` | Whether push can reach this device right now (below). Implemented once in the base class. | ### PushNotificationEvent ```dart class PushNotificationEvent { final Map data; const PushNotificationEvent(this.data); } ``` `data` is the notification's `additionalData` payload (mobile) or the same field from the JS event (web). ### PushIdentityChange ```dart class PushIdentityChange { final String? externalId; final String? subscriptionId; final bool? optedIn; const PushIdentityChange({this.externalId, this.subscriptionId, this.optedIn}); } ``` Every field is nullable because one SDK event reports only part of the state: a user change carries the external id, a subscription change carries the subscription id and the opt-in flag. A `null` field means "this event did not report it", never "it is empty". ### Reachability `PushDriver.reachability()` derives a four-state answer, so every driver answers the same way: | State | Meaning | | :--- | :--- | | `PushReachability.unavailable` | No platform driver here (`isSupported` is `false`), or one whose SDK never started (`isInitialized` is `false`), so a request would only be refused. | | `PushReachability.blocked` | Permission was denied and the platform will not re-prompt. The app has to point at the OS or browser setting. `requestPermission()` raises no OS dialog: on iOS and Android it shows OneSignal's settings fallback while `fallback_to_settings` is on, and on web, or with it off, nothing at all. | | `PushReachability.off` | Never asked, or asked and not opted in. Safe to call `requestPermission()`. | | `PushReachability.on` | Permitted, opted in and holding a subscription id: the only state a push can reach. | ```dart import 'package:magic_notifications/magic_notifications.dart'; Future currentReachability() async { final reachability = await Notify.manager.pushDriver.reachability(); return reachability; } ``` This is the read a soft prompt gates on before showing itself, and the read that answers "can I send this device a push" without raising the OS dialog. ## OneSignalDriver (iOS and Android) `OneSignalDriver` wraps the `onesignal_flutter` package. | Behaviour | Detail | | :--- | :--- | | `isSupported` | `true` on iOS and Android only | | `initialize` | Throws `NotificationException` with code `PLATFORM_NOT_SUPPORTED` on another platform and `MISSING_APP_ID` when `app_id` is blank; otherwise starts the SDK and attaches the foreground, click, permission and user observers | | `login` and `requestPermission` | Throw `NOT_INITIALIZED` when called before `initialize`; `logout`, `optIn` and `optOut` return quietly | | `permissionState()` | Maps the native permission; on platforms that report a denied state without a tri-state it asks the SDK whether a prompt would still show, so a never-asked device reads `notDetermined` | | `requestPermission()` | Passes `notifications.push.fallback_to_settings` to the SDK as its settings fallback for a denied device | | `canOpenPlatformSettings` | Follows `fallback_to_settings` (default `true`) | | `openPlatformSettings()` | Opens the app's own notification settings page | > [!NOTE] > The `NotificationException` codes are programmer errors: handle them at app startup. The provider catches an initialisation failure, logs it and records it on `NotificationServiceProvider.pushInitializationError`, so a broken push setup can be told apart from a build with no push. ### Listening to Events Prefer the manager's streams over the driver's own. They are filtered to the signed-in identity, and `onPushClicked` holds taps that arrive before anything listens, which is the cold-start case, and replays them when a listener attaches. ```dart import 'package:magic/magic.dart'; import 'package:magic_notifications/magic_notifications.dart'; void listenToPush() { Notify.manager.onPushReceived.listen((event) { final title = event.data['title']; // show an in-app banner }); Notify.manager.onPushClicked.listen((event) { // `event.data` is the notification's `additionalData`, so a destination is // only here when the backend put it there. Four keys, first match wins, // because that is what `magic_deeplink`'s own handler looks for. final url = event.data['url'] ?? event.data['deep_link'] ?? event.data['link'] ?? event.data['uri']; // Guarded: a notification with nowhere to go is a valid notification. if (url is String && url.isNotEmpty) MagicRoute.to(url); }); } ``` A push received in the foreground also triggers a `fetchNotifications()`, so the in-app list catches up. > [!WARNING] > OneSignal's Launch URL and `additionalData` are different fields. `OneSignalMessage::setUrl(...)` sets the first, which the SDK acts on itself on every platform and which never reaches `event.data`. A destination your own code routes from has to go through `setData(...)`, which is also OneSignal's own recommendation for mobile push. See [Laravel Backend Setup](https://anilcancakir.com/magic/docs/notifications/basics/laravel-backend-setup.md#onesignal-push) for the `toOneSignal` shape and for what sending both costs on iOS. ### Opening a screen from a tap The snippet above is the whole of what this package does about a tap: it hands you the payload and stops. **Nothing here routes anywhere**, and a tapped push that opens the app on its own initial route rather than on the notification's screen is this package working as built. The ecosystem's answer is `magic_deeplink`, and the wiring between the two is already done in both directions: - `DeeplinkServiceProvider` attaches `OneSignalDeeplinkHandler` to this package's click stream whenever `notifications` is bound, so no consumer code joins them. - That handler reads the first of `url`, `deep_link`, `link` or `uri` it finds in the payload, which is the same key list the `magic-starter-laravel` OneSignal channel writes. What is not done for you is the last link: **an app has to register a handler of its own**, because `magic_deeplink` publishes no handler stubs at install time. Without one, `DeeplinkManager.handleUri` walks an empty list, returns `false`, and nothing is logged. A pipeline that is correct at every step and does nothing at the end looks exactly like a notification that was never tapped. ```dart import 'package:magic/magic.dart'; import 'package:magic_deeplink/magic_deeplink.dart'; class AppServiceProvider extends ServiceProvider { AppServiceProvider(super.app); @override void register() {} @override Future boot() async { app.make('deeplinks').registerHandler( RouteDeeplinkHandler(paths: const ['/notifications', '/orders/:id']), ); } } ``` `RouteDeeplinkHandler` navigates to the path the link names through `MagicRoute.to`, so the paths you list are your own in-app routes. Handlers form a first-match chain in registration order; write your own `DeeplinkHandler` when a tap has to do something other than navigate. See [magic_deeplink handlers](https://anilcancakir.com/magic/docs/deeplink/basics/handlers) and its [installation guide](https://anilcancakir.com/magic/docs/deeplink/getting-started/installation) for the handler chain and the platform association files (`apple-app-site-association`, `assetlinks.json`) a Universal or App Link needs before any of this is reached. ## OneSignalWebDriver (Web) `OneSignalWebDriver` talks to the OneSignal Web SDK v16 through JavaScript interop (`OneSignalJsInterop`). | Behaviour | Detail | | :--- | :--- | | `isSupported` | `true` on web only | | `initialize` | Throws `PLATFORM_NOT_SUPPORTED` off web, `MISSING_APP_ID` for a blank `app_id`, and `SDK_NOT_AVAILABLE` when the OneSignal script is not loaded in `web/index.html`. It passes `safari_web_id`, `notify_button_enabled`, `service_worker_path` and `service_worker_scope` to the SDK, plus a click handler that matches by origin and focuses an open tab. | | `login` and `requestPermission` | Throw `NOT_INITIALIZED` before `initialize` | | `permissionState()` | Reads the browser's own `Notification.permission` | | `oneSignalId` | The OneSignal internal user id, or `null` before initialisation | `OneSignalWebDriver` is not exported from the package barrel, so reach the web driver through the `PushDriver` contract (`Notify.manager.pushDriver`); `oneSignalId` is a member of the concrete class only. The page must load the SDK script, and must not call `OneSignal.init()` itself: the driver initialises from config. The installer adds the right `