Skip to content
Flutter SDK

Flutter messaging

Push permission and device registration, the in-app inbox, notification preferences, safe deep links and local reminders.

On this page

core.messaging (MessagingClient) handles push device registration, the inbox and notification preferences. core.deepLinks and core.routeGate check and hold the routes that notifications open. ReminderPlanner schedules local reminders.

core.messaging throws FEATURE_UNAVAILABLE when neither push nor in_app is in messagingChannels. Check messaging.pushEnabled and messaging.inboxEnabled to decide which parts to show.

Provider setup: Firebase, FCM and APNs. Endpoints: Messaging API.

Warning

Not yet enabled: real push. Device registration, permission handling and payload checks are fixture-tested with a fake PushBridge. The FCM adapter's foreground, background and terminated tap handling has not been run, because no Firebase config exists for the reference app. No push has been sent to a device.

Attach push

Dart
await Firebase.initializeApp();            // needs GoogleService-Info.plist / google-services.json
final messaging = core.messaging;
await messaging.attach(FcmPushBridge());   // reference adapter: examples/flutter-reference/lib/adapters/fcm_push.dart
await messaging.registerDevice();

If Firebase fails to initialize, skip attach. The inbox and local reminders still work. The reference app does exactly this.

The PushBridge port:

Dart
abstract class PushBridge {
  String get platform; // 'android' | 'ios'
  Future<PushPermission> permission();
  Future<PushPermission> requestPermission();
  Future<String?> token();                       // null until APNs is ready on iOS
  Stream<String> get onTokenRefresh;
  Stream<Map<String, Object?>> get onOpened;      // taps while running or in background
  Future<Map<String, Object?>?> initialOpen();    // tap that cold-started the app
  Future<void> deleteToken();
}

Device registration

registerDevice() sends PUT /v1/messaging/devices with installation_id, platform, permission_status, app_version, and push_token, locale and timezone when they are known. It is an idempotent upsert. The key is derived from the installation, token, permission and user. It does nothing when signed out or when push is disabled.

The SDK registers again automatically:

  • when the push token refreshes (after attach);
  • after requestPermission(), if signed in;
  • after a sign-in or account switch, but only if core.messaging had already been created.

On core.logout() the SDK detaches the device (DELETE /v1/messaging/devices/{installation_id}). If that fails with a retryable error, the detach is stored and retried before the next registration.

Permission

Keep the OS permission separate from the in-app preference.

Dart
final perm = await messaging.permission(); // notDetermined | provisional | granted | denied | unavailable

if (await messaging.shouldOfferPermissionCard()) {
  // show your own card explaining the benefit, then:
  final result = await messaging.requestPermission(); // only after the user taps "Enable"
  // or, on "Not now":
  await messaging.declinePermissionCard();             // remembered; the card is not offered again
}

shouldOfferPermissionCard() is true only when the OS has not been asked and the user has not chosen "Not now". NotificationPermissionCard implements this, and pushPermissionLabel(perm) gives a label for each state.

Inbox

Dart
final page = await messaging.inbox();              // Page<InboxItem>, page.unreadCount
final next = page.nextCursor == null ? null : await messaging.inbox(cursor: page.nextCursor);
final offline = await messaging.cachedInbox();     // first page, this user only
await messaging.markRead(page.items.first.id);     // idempotent

The SDK drops any item whose userId is not the current user's, as defence in depth. It caches the first page per user and clears it on sign-out or account switch. InboxItem has isRead and isExpired(now).

Notification preferences

Dart
await messaging.savePreferences(NotificationPreferences(
  quietHoursStart: '22:00',
  quietHoursEnd: '07:00',
  timezone: 'Asia/Kolkata',
  engagementEnabled: true,
  dailyCap: 2, // 0–20
));

Warning

Not yet enabled: reading preferences back. The contract has only PUT /v1/messaging/preferences, with no GET, so the SDK cannot load the saved values. Keep the user's last choice in your app and send the full object each time.

Marketing consent (marketing_push and others) is separate from these preferences. Record it with privacy.setConsent.

Only allowlisted, versioned actions are accepted: open_inbox, open_content and open_subscription. The SDK does not subscribe to onOpened for you. Wire it yourself:

Dart
void onPushData(Map<String, Object?> data) {
  final decision = core.deepLinks.fromPush(data);
  if (!decision.accepted) return; // decision.rejection says why
  final route = core.routeGate.offer(decision.route!, signedIn: core.session.isSignedIn);
  if (route != null) openRoute(route); // otherwise it is held until sign-in
}

push.onOpened.listen(onPushData);
final cold = await push.initialOpen();
if (cold != null) onPushData(cold);

// After a successful sign-in:
final held = core.routeGate.takeAfterSignIn();
if (held != null) openRoute(held);

The push data payload is {v: "1", nid, action, app_id, env, ref?}. fromPush rejects it (LinkRejection) if:

  • v is not "1" (unsupportedVersion);
  • app_id or env belongs to another app or environment (otherApp, otherEnvironment);
  • any value looks like a URL (externalUrl);
  • the action is not on the list (unknownAction);
  • ref is missing or malformed for open_content (badId);
  • a nid was already seen, out of the last 200 (duplicate).

App links use fromUri. Only <deepLinkScheme>://<appId>/inbox[/<id>], /content/<ref> and /subscription are accepted, with no query, fragment or user info.

AppRoute has action (AppAction.openInbox, openContent, openSubscription), id and notificationId. Every route requires a session. On sign-out the gate drops any held route.

Local reminders

ReminderPlanner builds a rolling, bounded schedule in the user's IANA timezone and reconciles it with the OS through a LocalNotificationsBridge. The reference adapter is local_notifications.dart.

Dart
import 'package:timezone/data/latest.dart' as tzdata;
import 'package:timezone/timezone.dart' as tz;

tzdata.initializeTimeZones();
final planner = ReminderPlanner(); // capacity 32 (below the iOS 64 limit), 14-day horizon
final plan = planner.plan(
  [const ReminderRule(id: 'daily', hour: 20, minute: 0, weekdays: {1, 2, 3, 4, 5, 6, 7}, title: 'Lesson time', body: 'Your next lesson is ready')],
  location: tz.getLocation('Asia/Kolkata'),
  nowUtc: DateTime.now().toUtc(),
  ownerTag: core.session.userId ?? 'signed-out',
);
await planner.sync(bridge, plan);          // call on foreground, timezone change, boot, account switch
await planner.cancelOwner(bridge, oldTag); // on sign-out or account switch

Occurrence ids are stable, so re-syncing does not create duplicates. A local time that does not exist on a DST change day still fires once, shifted forward. Reminders are inexact and best effort. They are not medical or critical alarms.

Warning

Not yet enabled: rescheduling reminders after an Android reboot. The boot receiver is documented in INTEGRATION.md but has not been tested on a device.