On this page14 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. The Device Address
  4. 2. register and onRegistered
  5. 3. Logout: unregister
  6. 4. The Older Token API
  7. 5. Topics: Many Devices at Once
  8. Code Examples
  9. Common Beginner Mistakes
  10. Best Practices
  11. Practice Questions
  12. Practice Answers
  13. Key Takeaways
  14. Full Code (Copy-Paste Reference)

Lecture 009: The FCM Device Token

Category2: Push Notifications
Lecture009 of 014
Estimated video length14 min
TargetFlutter 3.44 · Dart 3.12 · firebase_messaging 17
LevelIntermediate

To send a notification to one phone, you need that phone's address. We register the app with FCM, receive its ID, keep it up to date on the server, and learn about topics for sending to many phones at once.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Practice Questions · Answers · Takeaways · Full Code


Prerequisites

Lecture 005: messaging set up, permission granted.


Learning Objectives

  • Register the app with register() and receive its ID from onRegistered
  • Unregister on logout with unregister()
  • Recognise the older getToken() / onTokenRefresh code
  • Save the ID where your server can use it
  • Subscribe to topics

1. The Device Address

Every install of your app on a device gets an ID that FCM can deliver to. Your server stores it per user and sends a message to it to reach exactly that device.

firebase_messaging 17 changed how you get it:

New way (17+)Older way (still works, deprecated)
Ask for the IDregister()getToken()
Receive itonRegistered stream: a Firebase Installation ID (FID)the getToken() result: a registration token
It changesonRegistered fires againonTokenRefresh
Stop (logout)unregister() + onUnregistereddeleteToken()

2. register and onRegistered

dart
FirebaseMessaging.instance.onRegistered.listen((String fid) {
  print('FCM registered: $fid');
  // send fid to your server
});

await FirebaseMessaging.instance.register();

Listen first, then register: register() only starts the process; the ID arrives on the stream when FCM has finished, and again whenever it changes. Wrap register() in a try: it fails without network or Google Play services.

On iOS, registration waits for Apple's APNs token, so set up the APNs key (Lecture 005) and test on a device.

3. Logout: unregister

dart
FirebaseMessaging.instance.onUnregistered.listen((String fid) {
  // remove fid from your server
});

await FirebaseMessaging.instance.unregister();

After this, messages to that ID fail: the next person to use the phone won't get the previous user's notifications.

4. The Older Token API

Most tutorials and existing apps (and the notes this course started from) use:

dart
final String? token = await FirebaseMessaging.instance.getToken();
FirebaseMessaging.instance.onTokenRefresh.listen((newToken) { /* update server */ });

It still works in version 17 but shows a deprecation warning. On iOS it throws apns-token-not-set if called before APNs is ready. Use it when your server or a tool still expects a registration token: for example, if the console's Send test message box asks for an "FCM registration token". New code should use register().

5. Topics: Many Devices at Once

Instead of collecting IDs, devices can subscribe to a topic name:

dart
await FirebaseMessaging.instance.subscribeToTopic('promotions');
await FirebaseMessaging.instance.unsubscribeFromTopic('promotions');

The console (or your server) sends one message to the topic promotions, and every subscribed device gets it. Topic names: letters, digits and -_.~%.


Code Examples

Example 1: Registration in the Helper Class

dart
// lib/firebase_notification_handling.dart
import 'dart:async';

static StreamSubscription<String>? _registeredSub;

static Future<void> registerWithFcm() async {
  _registeredSub ??= FirebaseMessaging.instance.onRegistered.listen((fid) {
    debugPrint('FCM_REGISTERED $fid');
    // updateIdInDatabase(fid);
  });

  try {
    await FirebaseMessaging.instance.register();
  } catch (e) {
    debugPrint('FCM_REGISTER_ERROR $e');
  }
}

Call it from initState after registerNotificationPermission(). The debug console prints FCM_REGISTERED … once registration completes: store that value on your server with the user.

Example 2: Topic Toggle

dart
SwitchListTile(
  title: const Text('Promotions'),
  value: wantsPromos,
  onChanged: (on) async {
    setState(() => wantsPromos = on);
    if (on) {
      await FirebaseMessaging.instance.subscribeToTopic('promotions');
    } else {
      await FirebaseMessaging.instance.unsubscribeFromTopic('promotions');
    }
  },
)

Send a campaign to the topic promotions in the console: only phones with the switch on get it.


Common Beginner Mistakes

1. Calling register() before listening: the ID can arrive before your listener exists. Listen first.

2. Hard-coding an ID: it changes on reinstall; keep the latest one per user on your server.

3. Mixing the two APIs: an FID and a registration token are different values. Send your server the kind it expects, and use one API throughout the app.


Best Practices

  • Save the ID with the signed-in user's ID (Firestore or your API); update it whenever onRegistered fires.
  • Call unregister() on logout and remove the ID from your server.
  • Use topics for broadcast messages (news, promotions); device IDs for personal ones.

Practice Questions

  1. Which method starts registration, and where does the ID arrive?
  2. Why listen to onRegistered before calling register()?
  3. What should happen on logout?
  4. How do you send one message to everyone interested in sports?

Practice Answers

  1. register(); the onRegistered stream.
  2. The ID might arrive before a listener exists and be missed.
  3. Call unregister() and remove the ID from your server.
  4. Have the app subscribeToTopic('sports'), then send to the topic sports.

Key Takeaways

  • register() + onRegistered give this device's FCM address (an FID) in version 17+.
  • The ID can change: keep your server updated from onRegistered.
  • unregister() on logout.
  • getToken() / onTokenRefresh is the older, deprecated way; topics broadcast to many devices.

Full Code (Copy-Paste Reference)

Everything the app needs up to and including this lecture, file by file. dialog_promo_code.dart and notification_status.dart are unchanged from Lecture 007.

lib/firebase_notification_handling.dart

dart
import 'dart:async';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'dialog_promo_code.dart';
import 'notification_status.dart';

class FirebaseNotificationHandling {
  static Future<void> registerNotificationPermission() async {
    final settings = await FirebaseMessaging.instance.requestPermission(
      alert: true,
      badge: true,
      sound: true,
    );
    print('Notification permission: ${settings.authorizationStatus}');

    await FirebaseMessaging.instance
        .setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );
  }

  static void firebaseOnMessageNotificationHandle(
      GlobalKey<NavigatorState> navigatorKey) {
    FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage? message) {
      if (message != null) {
        notificationHandler(navigatorKey, 2, message);
      }
    });

    FirebaseMessaging.onMessageOpenedApp.listen((message) {
      notificationHandler(navigatorKey, 2, message);
    });

    FirebaseMessaging.onMessage.listen((message) {
      notificationHandler(navigatorKey, 1, message);
    });
  }

  static Future<void> notificationHandler(GlobalKey<NavigatorState> navigatorKey,
      int delaySeconds, RemoteMessage message) async {
    final data = message.data;
    final type = data['noti_type'] as String? ?? '';
    if (type != NotificationStatus.promoAdded && type != NotificationStatus.general) {
      return;
    }

    final title = data['noti_title'] as String? ?? '';
    final body = data['noti_body'] as String? ?? '';
    final imageUrl = data['image_url'] as String? ?? '';

    await Future.delayed(Duration(seconds: delaySeconds));

    final context = navigatorKey.currentContext;
    if (context == null || !context.mounted) return;

    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (_) => DialogPromoCode(title: title, body: body, type: type, imageUrl: imageUrl),
    );
  }

  static StreamSubscription<String>? _registeredSub;

  /// Registers this device with FCM and keeps listening for the id to change.
  /// Listening is set up BEFORE register() is called, so the first id can't be missed.
  static Future<void> registerWithFcm() async {
    _registeredSub ??= FirebaseMessaging.instance.onRegistered.listen((fid) {
      debugPrint('FCM_REGISTERED $fid');
      // updateIdInDatabase(fid);
    });

    try {
      await FirebaseMessaging.instance.register();
    } catch (e) {
      // No network or no Google Play services - don't let this crash startup.
      debugPrint('FCM_REGISTER_ERROR $e');
    }
  }
}

lib/main.dart

dart
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';

import 'firebase_notification_handling.dart';
import 'firebase_options.dart';

@pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  print('Background message: ${message.data}');
}

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  static final navigatorKey = GlobalKey<NavigatorState>();

  @override
  void initState() {
    super.initState();
    FirebaseNotificationHandling.registerNotificationPermission();
    FirebaseNotificationHandling.firebaseOnMessageNotificationHandle(navigatorKey);
    FirebaseNotificationHandling.registerWithFcm();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: navigatorKey,
      home: const HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Notify Demo')),
      body: const Center(child: Text('Allow notifications when prompted')),
    );
  }
}