Push notifications: mobile app guide (Flutter)
Step-by-step guide for the mobile team: what to build in the Flutter app so the phone gets a system notification for every new alert on the user's devices. The wire messages and the payload are specified in Push notifications; this page is how to use them.
:::note Platform support (2026-11-11)
Android and iOS. The backend accepts "platform": "ios" and sends iOS
pushes as of 2026-11-11 (in code; live on dev after the next deploy). The
iOS app (com..solar.crowninverter) is registered in the Firebase project;
delivery also needs the APNs key uploaded there and the Xcode capabilities
(see iOS setup).
:::
What you are building
The app has five jobs:
- Set up Firebase and the notification channels.
- Ask the user for permission.
- Register the FCM token with the backend, and keep it registered.
- Unregister it on sign-out.
- Handle taps, and alerts that arrive while the app is open.
1. Firebase setup
The Firebase project for dev is cse-datalogger (it replaced
crown-solar-energy-dev on 2026-11-12). Add the Android app and the iOS
app (com..solar.crowninverter) to it if they are not there yet, and
rebuild with the new google-services.json / GoogleService-Info.plist;
a build still on the old project gets tokens the backend rejects. Ask the backend team for access to the Firebase
console if you don't have it.
-
Add the packages:
flutter pub add firebase_core firebase_messaging flutter_local_notifications -
Generate the Firebase config with the FlutterFire CLI. It writes
android/app/google-services.json,ios/Runner/GoogleService-Info.plistandlib/firebase_options.dart, and wires the Google Services Gradle plugin:dart pub global activate flutterfire_cliflutterfire configure --project=cse-datalogger --platforms=android,iosgoogle-services.jsonandGoogleService-Info.plistare client configuration, not secrets; they ship inside every build and are fine to commit. Never put the backend's service-account key (a file with aprivate_keyin it) in the app or its repository. -
Initialise Firebase before
runApp:Future<void> main() async {WidgetsFlutterBinding.ensureInitialized();await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);await PushChannels.create();runApp(const App());}
2. Notification channels
The backend sends every alert on one of three Android channels, by severity. Create them at startup, before the first notification can arrive. Users can then mute info alerts and keep critical ones loud, from Android's own settings.
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class PushChannels {
static const critical = AndroidNotificationChannel(
'alerts_critical', 'Critical alerts',
description: 'Faults that stop the inverter or need action now',
importance: Importance.max,
);
static const warning = AndroidNotificationChannel(
'alerts_warning', 'Warnings',
description: 'Problems that need attention soon, such as a logger going offline',
importance: Importance.high,
);
static const info = AndroidNotificationChannel(
'alerts_info', 'Information',
description: 'Informational device events',
importance: Importance.defaultImportance,
);
static final plugin = FlutterLocalNotificationsPlugin();
static Future<void> create() async {
final android = plugin.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>();
for (final c in [critical, warning, info]) {
await android?.createNotificationChannel(c);
}
}
}
The channel ids must match exactly: alerts_critical, alerts_warning,
alerts_info. A notification for a channel the app has not created still
shows, on Firebase's default channel, so a mismatch is never a lost alert.
But the user then loses per-severity control.
Optionally, make alerts_warning the default channel for anything else, in
android/app/src/main/AndroidManifest.xml inside <application>:
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="alerts_warning" />
3. Permission
Android 13 and later need the POST_NOTIFICATIONS runtime permission, and
iOS always asks. requestPermission() covers both (a no-op on older
Android):
final settings = await FirebaseMessaging.instance.requestPermission();
final allowed = settings.authorizationStatus == AuthorizationStatus.authorized;
Ask at a moment the user understands, for example on the alerts screen or
right after they add their first device ("Get notified when your inverter
has a fault?"), not on first launch. iOS shows the system prompt once and
Android at most twice; after a second "Don't allow" the only way back is the app's
system settings, so show a link there when allowed is false.
Register the token (next step) whether or not permission was granted. If the user grants it later in system settings, notifications start arriving without another registration.
4. Register the token
Send register_push_token over the app's existing WebSocket:
{"type": "register_push_token",
"userId": "<the signed-in user's id>",
"token": "<FirebaseMessaging.instance.getToken()>",
"platform": "android"} // "ios" on an iPhone
The reply is {"type": "push_token_result", "action": "register", "ok": true}.
When to send it. Registration is idempotent; sending it again just refreshes it. Send it:
- after sign-in;
- after every WebSocket (re)connect. If the connection authenticates
with a realtime ticket, send it after
auth_resultcomes backok; - whenever Firebase rotates the token (
onTokenRefresh).
Which user. Push goes to the device's owner: the user whose
userId registered the device. A user who doesn't own any device gets no
pushes. On a connection authenticated with a realtime ticket, the gateway
uses the ticket's user and ignores userId; without a ticket (allowed on
dev), it trusts userId. See
Authentication.
A service that does all of this:
import 'dart:async';
import 'dart:io' show Platform;
import 'package:firebase_messaging/firebase_messaging.dart';
class PushRegistration {
PushRegistration(this.send);
/// Sends one JSON message on the current WebSocket.
final void Function(Map<String, dynamic> message) send;
String? _userId;
StreamSubscription<String>? _refreshSub;
/// Call after sign-in, and after every WebSocket (re)connect
/// (after `auth_result` ok when using tickets).
Future<void> register(String userId) async {
_userId = userId;
_refreshSub ??= FirebaseMessaging.instance.onTokenRefresh.listen((token) {
final id = _userId;
if (id != null) _sendRegister(id, token);
});
// iOS: FCM needs the APNs token first, and getToken() throws without
// it. It can be null right after launch; the next reconnect retries.
if (Platform.isIOS && await FirebaseMessaging.instance.getAPNSToken() == null) {
return;
}
final token = await FirebaseMessaging.instance.getToken();
if (token != null) _sendRegister(userId, token);
}
/// Call on sign-out, while the WebSocket is still open.
Future<void> unregister() async {
final id = _userId;
_userId = null;
await _refreshSub?.cancel();
_refreshSub = null;
if (id == null) return;
final token = await FirebaseMessaging.instance.getToken();
if (token != null) {
send({'type': 'unregister_push_token', 'userId': id, 'token': token});
}
// Invalidates this install's token at Firebase too, so the backend
// drops it on the next send even if the message above never arrived.
await FirebaseMessaging.instance.deleteToken();
}
void _sendRegister(String userId, String token) {
send({
'type': 'register_push_token',
'userId': userId,
'token': token,
'platform': Platform.isIOS ? 'ios' : 'android',
});
}
/// Route `push_token_result` replies here.
void onResult(Map<String, dynamic> msg) {
if (msg['ok'] != true) {
// Validation errors are bugs in the request; database errors
// ("could not register the push token; try again") are transient and
// the next reconnect re-registers anyway. Log, don't alert the user.
debugPrint('push ${msg['action']} failed: ${msg['error']}');
}
}
}
Rules worth knowing:
- One token belongs to one user. If a second user signs in on the same phone and registers, the token moves to them and the first user's alerts stop arriving there. That is what you want on a shared phone.
- A user can have at most 10 tokens (10 phones or reinstalls). The 11th drops the one refreshed longest ago.
- Never log the token, and never show it in the UI outside a debug build. It addresses this person's phone.
5. Sign-out
Call PushRegistration.unregister() before closing the WebSocket. The
reply is always ok: true, even if the token wasn't registered; that is
deliberate. deleteToken() makes sure a sign-out that happened offline
still stops notifications: Firebase reports the old token as dead on the
next send, and the backend deletes it.
6. Tapping a notification
When the app is in the background or closed, Android or iOS shows the notification itself. You handle the tap:
Future<void> setUpPushTaps(void Function(RemoteMessage) open) async {
// App was closed and launched by the tap.
final initial = await FirebaseMessaging.instance.getInitialMessage();
if (initial != null) open(initial);
// App was in the background.
FirebaseMessaging.onMessageOpenedApp.listen(open);
}
void openFromPush(RemoteMessage m) {
final d = m.data;
if (d['type'] != 'alert') return;
final count = int.tryParse(d['count'] ?? '1') ?? 1;
if (count > 1) {
// Several alerts in one notification: open the device's alert list.
router.push('/devices/${d['deviceKey']}/alerts');
} else {
router.push('/alerts/${d['alertId']}');
}
}
Every data value is a string. The keys:
| Key | Use |
|---|---|
type | Always "alert" today. Ignore messages with another type, so new types can be added later without breaking old app versions |
alertId | The alert to open. Same id as get_alerts returns |
alertIds | Comma-separated ids of every alert in this notification |
count | How many alerts it covers. > 1: open the device's alert list |
deviceKey | The device (the key every other message uses) |
plantId | The device's plant |
loggerId | The logger that raised the first alert, for display only |
code | The first alert's catalog code, e.g. aotai.F01 |
severity | critical, warning or info: the highest in the notification |
The alert may already be resolved by the time the user taps (a short grid
dip). Fetch it with get_alerts and show its current state rather than
assuming it is still open.
7. While the app is open
Android does not display a notification while the app is in the
foreground, and neither does iOS unless the app opts in with
setForegroundNotificationPresentationOptions; leave that off. It is delivered to FirebaseMessaging.onMessage instead. The
app is connected then and gets the same alert as alerts_changed on the
live feed, so:
- show an in-app banner or update the bell from
alerts_changed; - don't post a second system notification from
onMessage. At most use it as a fallback when the WebSocket is down.
FirebaseMessaging.onMessage.listen((m) {
if (!ws.isConnected) {
showInAppBanner(m.notification?.title, m.notification?.body, m.data);
}
});
No onBackgroundMessage handler is needed. The backend sends notification
messages, which Android and iOS display themselves; the app does no work
in the background.
What the user sees
| Case | Notification |
|---|---|
| One alert | Critical: Grid over-voltage Inverter AT5K2400123 — Grid voltage above limit |
| Several alerts from the same scan | Critical: 3 new alerts Inverter AT5K2400123 — Grid Loss, Under Upv1, Under Upv2 |
| Logger silent for 5 minutes | Warning: Logger Offline Inverter AT5K2400123 — This logger has not reported in over 5 minutes. |
Logger <loggerId> replaces Inverter <serial> when the serial isn't known
yet. Critical and warning are sent at high priority (delivered at once even
when the phone dozes; apns-priority 10 on iOS); info at normal priority
(5 on iOS).
Not pushed: an alert resolving, an alert older than 15 minutes when it reaches the sender (backlog after an outage), and fleet-wide offline bursts. All of those still show in the app's alert list. See What is pushed.
Notification history in the app (optional)
The backend keeps a 90-day inbox of the pushes it delivered to each user,
with an unread count: get_notification_deliveries and
mark_notifications_read, documented in the web console's
Notification inbox. Those
messages need a connection authenticated with a realtime ticket. The
alert list is the source of truth either way; build
this only if the design calls for a "notifications" screen separate from
alerts.
Testing
- Install a build with the steps above on a real Android phone with Google Play services (an emulator works if its image includes Google Play), or on a real iPhone. The iOS Simulator cannot receive remote notifications reliably; test iOS on a device.
- Sign in as the user who owns the bench inverter, and accept the
permission prompt. Check the app log for
push_token_resultwithok: true. - Trigger an alert. The simplest is to unplug the logger for 6 minutes ("Logger Offline", warning). Or disconnect the battery BMS cable or the grid input for a real inverter fault, which pushes within seconds.
- The notification should arrive within a few seconds of the alert. Tap it and check the right alert opens. Repeat with the app closed and with the app open (in-app banner, no system notification).
- Sign out, trigger another alert, and check nothing arrives.
To test only the app side, without the backend: Firebase console → Messaging → New campaign → Notifications → Send test message, with the token from a debug build.
The backend team can confirm each send in the persistence-worker log
(push sent … tokens=1 sent=1).
Troubleshooting
| Symptom | Likely cause |
|---|---|
push_token_result ok: false, platform must be "android", "ios" or "web" | platform missing or misspelled |
iOS: ok: true but nothing arrives, and the backend log shows push send failed … THIRD_PARTY_AUTH_ERROR | The APNs key is missing or wrong in the Firebase project (see iOS setup). The token is kept and works once the key is fixed |
| iOS: nothing arrives, no failure in the backend log | The Push Notifications capability or the APNs entitlement is missing from the build, or the build's APNs environment (development vs production) doesn't match the key |
ok: true but nothing ever arrives | The signed-in user doesn't own the device; notifications are off for the app in Android settings; or the app was built against a different Firebase project than the backend sends through (the backend then deletes the token as SENDER_ID_MISMATCH) |
| Arrives late, or not at all, on some phones | Manufacturer battery optimisation (Xiaomi, Oppo, Vivo, Huawei). Point users to "allow background activity" for the app |
| Nothing on Huawei phones sold since 2019 | No Google Play services, so no FCM. Not supported |
| Notification shows on "Miscellaneous" instead of the alert channels | PushChannels.create() didn't run before the first notification |
| Two identical notifications | Should replace, not stack: the backend sets the same tag on a resend. Report it with the time and device to the backend team |
iOS setup
The Flutter code above is the same on iOS. In addition:
- Xcode capabilities on the Runner target: Push Notifications, and Background Modes → Remote notifications.
- APNs key in Firebase (done once by whoever holds the Apple Developer
account): create an APNs authentication key (
.p8) in the Apple Developer portal and upload it in Firebase console → Project settings → Cloud Messaging → Apple app configuration, with its Key ID and the Team ID. The key goes to Firebase only, never into a repository. Without it the backend's sends fail withTHIRD_PARTY_AUTH_ERROR. - Register with
"platform": "ios". The backend sends the samenotificationanddataas on Android, with anapnsblock (priority, expiry, collapse id = the alert id, default sound). FCM puts thedatakeys at the top level of the APNs payload, soRemoteMessage.datais the same as on Android. - There are no channels on iOS;
PushChannels.create()does nothing there.