magic_notifications
Notifications for a Magic app. The backend creates inbox rows and the Notify facade reads them (notifications(), fetchNotifications(), markAsRead); NotificationsListView, NotificationPreferencesView and NotificationDropdown render them. Push goes through OneSignal (OneSignalDriver on iOS and Android, OneSignalWebDriver on web), and new rows arrive over a magic_socket channel with NotificationPoller as the fallback. The package has two channels, database and push, and no mail channel.
This skill covers magic_notifications only. The Magic framework itself (container, Config, Http, Vault, service providers) is the magic-framework skill; the socket layer is magic_socket, and routing a tapped push is magic_deeplink.
Install
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
Requires Dart >=3.13, Flutter >=3.47 and magic ^1.0.0. plugin:install registers NotificationServiceProvider in lib/config/app.dart and the commands with dowel; the package has no executable, so a command exists only after it. notifications:install writes lib/config/notifications.dart and the platform files, and wires lib/main.dart. Import only the barrel: package:magic_notifications/magic_notifications.dart.
Provider and config rules
- Register
NotificationServiceProvider:boot()registersDatabaseChannel, loads the persisted push intent, resolves the driver named bynotifications.push.driver, registersPushChanneland initialises the driver whennotifications.push.app_idis set. A build with nodriverkey is supported: everything except push keeps working. boot()starts no polling. StartNotify.startPolling()andstartRealtimefrom the authenticated layout, so nothing runs while nobody is signed in.- A blank
app_idleaves the driver uninitialised andreachability()atunavailable. A failed initialisation does not stop boot; readNotificationServiceProvider.pushInitializationError. - A
drivervalue nothing was registered under is logged at error level and push stays off. A driver of your own isNotify.extend('name', () => MyDriver())before the provider boots. polling_intervalis clamped to 5 to 600 seconds and read when the poller is built; a value that is not anintreads as 30.notifications.database.enabledand themailandsoft_prompt.titlekeys the stub writes are read by no runtime code.
Channel rules
Notification.via()names channels;Notify.sendskips an unregistered name with a logged warning and an unavailable channel silently, tries every channel, and rethrows the first error after the last. Never name'mail': there is no mail channel.DatabaseChannel.senddoes nothing, because the backend writes the row. Do not use it to create inbox rows from the client.PushChannelis self-addressed and ships off. It posts toPOST /notifications/push-test, so it can only page the signed-in user, and it is available only when the driver is supported andnotifications.push.self_test_enabledistrue. Send push to other people from your backend.- A
Notifiablethat is not the signed-in user makesPushChannelthrowNotificationException(PUSH_RECIPIENT_NOT_AUTHENTICATED_USER); a failed answer throwsHTTP_<status>. Notificationclashes with Flutter's widgets library:import 'package:flutter/widgets.dart' hide Notification;.
Inbox rules
fetchNotifications()logs a failure and keeps the held list;fetchPaginatedNotificationsthrowsNotificationException(NOTIFICATIONS_FETCH_FAILED,NOTIFICATIONS_DECODE_FAILED), so an empty page always means an empty inbox.unreadCount()returns0on any failure.- A row decodes only when
datacarries stringtitleandbody; one bad row fails the whole list. - The client sends
pageandperPageand readsmeta.current_page,last_page,per_pageandtotal.unread-countmust answer{"count": n}at the top level: a{"data": {"count": n}}wrapper reads as0. markAsReadandmarkAllAsReadchange the held list first and refetch when the request throws. Magic'sHttpreturns an error status as aMagicResponseinstead of throwing, so an HTTP failure is not rolled back.deleteNotificationrestores the row and rethrows; a caller wanting silence adds acatch.- Signing out clears the held list. Call
Notify.logoutPush()on sign-out andNotify.initializePushafter sign-in, or the next person sees the previous person's rows.
Push rules
- The package declares no push identity. After sign-in call
Notify.initializePush('<prefix><id>'); on sign-outNotify.logoutPush(). The id is forwarded unchanged and the backend addresses the device by the same string, so one prefix (user_) must hold on both sides;notifications.push_state.external_id_prefixhas to match it.magic_starteralready does this for its apps. requestPushPermission()shows nothing once the OS has answered. Askreachability()(unavailable,blocked,off,on) orNotify.manager.pushPromptAdvice(declinedAt:)first;blockedneeds the OS or browser setting, and the app owns the decline timestamp.- A tapped push opens nothing.
onPushClickedhands overevent.data; routing is amagic_deeplinkhandler your app registers, or your own listener. Put the destination in OneSignalsetDataunderurl,deep_link,linkoruri:setUrlis the Launch URL and never reaches the payload. Notify.pushState.watch()reports device reachability to your backend. Nothing calls it for you, the provider included, so arm it once from a provider'sboot(); it stays off until bothreport_pathandrelease_pathare set, and one alone logs an error. Callrelease()beforeAuth.logout(), because the release needs the token.describePushUserUsingsends nothing untilshare_user_attributesistrue. A tag written from a client is user-tamperable: never trust it for a plan, role or entitlement.- Web push on iOS Safari reaches nobody until the site is added to the Home Screen. The page loads the OneSignal script and must not call
OneSignal.init(); the driver initialises from config. - iOS needs
aps-environmentdevelopmentfor Debug and Profile andproductionfor Release; the installer writes both entitlements files andnotifications:doctorreads them. The APNs key upload, the App Group and the Notification Service Extension stay manual.
Realtime rules
startRealtime(channel:)returnsfalseand changes nothing whenbroadcasting.defaultis unset, empty or'null', or whenchannelis empty, so the caller keeps polling. It needsmagic_socketregistered.- Call
startPolling()after it every time: polling is a no-op while the socket is live, and the manager arms its own stand-in poller while the channel is unsubscribed and stops it once the server confirms, refetching once. - The channel name is the caller's:
App.Models.User.{id}for a Laravel notifiable. The event isNotificationManager.realtimeEvent,notification.created, and the backend must name it inbroadcastAs(). A redelivered id replaces the held row.
Screens rules
Notify.viewseedsnotifications.listandnotifications.preferenceson first read.registerwraps or replaces one; askhasOverride(key)rather thanhas(key), which is true from the first read.- The package ships no translation catalogue. Add every
notifications.*key the screens andPushPromptuse to each locale, or a key renders as itself. NotificationsListView.onDeletereturnsFuture<bool>:truereloads the page,falseleaves it alone, a throw reloads.PushPromptHosttakes adeclinedVaultKeyof its own; it reads the value back as an ISO-8601 timestamp and treats anything else as never declined.
Recipes
Declare the push identity and arm delivery on sign-in, and undo both on sign-out:
import 'package:magic/magic.dart';
import 'package:magic_notifications/magic_notifications.dart';
// Once, from a provider's boot() after auth is registered; nothing else calls it.
void armPushState() {
Notify.pushState.watch();
}
Future<void> onSignIn(String userId) async {
await Notify.initializePush('user_$userId');
await Notify.startRealtime(channel: 'App.Models.User.$userId');
Notify.startPolling();
}
Future<void> onSignOut() async {
Notify.stopRealtime();
Notify.stopPolling();
if (Notify.pushState.isConfigured) await Notify.pushState.release();
await Notify.logoutPush();
await Auth.logout();
}
Define a notification the database and push channels both know about:
import 'package:magic_notifications/magic_notifications.dart';
class MonitorDownNotification extends Notification {
@override
List<String> via(Notifiable notifiable) => ['database', 'push'];
@override
Map<String, dynamic>? toDatabase(Notifiable notifiable) => {
'title': 'Monitor down',
'body': 'api.example.com is not responding',
};
@override
PushMessage? toPush(Notifiable notifiable) {
return PushMessage()
.heading('Monitor down')
.content('api.example.com is not responding')
.url('/monitors/1');
}
}
Ask before interrupting, then act on what the button can do:
import 'package:magic_notifications/magic_notifications.dart';
Future<void> remind(DateTime? declinedAt) async {
final PushPromptAdvice advice = await Notify.manager.pushPromptAdvice(
declinedAt: declinedAt,
);
if (!advice.show) return;
switch (advice.action) {
case PushPromptAction.request:
await Notify.requestPushPermission();
case PushPromptAction.openSettings:
await Notify.openPushSettings();
case PushPromptAction.instructions:
case PushPromptAction.none:
break;
}
}
Testing
No mocking library is needed. Boot Magic once with Magic.init(configFactories: []), call Notify.forgetDrivers() in setUp because the manager is a process-wide singleton (Notify.forgetView() after registering a screen), and mock a channel or driver by extending NotificationChannel or PushDriver. Http.fake stubs the backend:
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:magic/magic.dart';
import 'package:magic_notifications/magic_notifications.dart';
void main() {
setUpAll(() async {
WidgetsFlutterBinding.ensureInitialized();
await Magic.init(configFactories: []);
});
setUp(Notify.forgetDrivers);
test('fetchNotifications fills the stream', () async {
Http.fake(<String, MagicResponse>{
'notifications': Http.response(<String, dynamic>{
'data': [
{
'id': '1',
'type': 'monitor_down',
'data': {'title': 'Monitor down', 'body': 'api.example.com'},
'read_at': null,
'created_at': '2026-11-14T10:30:00Z',
},
],
}),
});
await Notify.fetchNotifications();
expect(await Notify.notifications().first, hasLength(1));
});
}
PushChannel tests set Config.set('notifications.push.self_test_enabled', true) first, since the channel ships off.