Sub topic 13
Sending to groups with topics
Sending to one registration token reaches one app installation. A topic lets you send once and reach every installation that subscribed to a named group, such as news, sports_scores, or promo_en. This chapter covers how topics work, how to subscribe from Flutter, how to send to them, and where they cause problems.
This chapter assumes you have already finished the earlier chapters. You should have Firebase set up in your Flutter app, notification permission granted, and a working FCM registration token. You should also know the difference between notification messages and data messages.
What a topic is
A topic is a string name that FCM keeps as a subscription list. The server does not need to know any device tokens. The flow looks like this:
- The app asks FCM to subscribe its registration token to a topic.
- FCM stores the link between that token and the topic.
- Your server sends one message addressed to the topic.
- FCM fans the message out to every subscribed token.
This is publish/subscribe (pub/sub) messaging. Your server is the publisher. Each device is a subscriber. The two sides never need to know about each other.
Topics fit content that many users share and that does not depend on one person's data. Examples are breaking news, a sports team, a product announcement, or a language-specific promotion. They do not fit personal messages such as "your order shipped". Use a token for those.
Subscribing from the app
The firebase_messaging plugin provides two methods on FirebaseMessaging.instance. Both return a Future<void>.
import 'package:firebase_messaging/firebase_messaging.dart';
Future<void> subscribeToNews() async {
await FirebaseMessaging.instance.subscribeToTopic('news');
}
Future<void> unsubscribeFromNews() async {
await FirebaseMessaging.instance.unsubscribeFromTopic('news');
}Some details are worth knowing:
- The device needs a network connection to subscribe. If the call fails, the subscription does not exist. Catch the error and retry later.
- Subscribing does not need notification permission. A device can be subscribed and still show nothing, because display depends on the permission you requested earlier.
- Subscribing to a topic you are already subscribed to is harmless.
- Subscriptions belong to the registration token. If the token changes, FCM normally carries topic subscriptions over when it rotates the token. If the app is uninstalled and reinstalled, the new installation has a new token and no subscriptions.
Topic names
Topic names must match the pattern [a-zA-Z0-9-_.~%]+. Do not include a /topics/ prefix when you call the plugin methods. Names are case-sensitive, so News and news are different topics.
A topic is created the first time a device subscribes to it. You do not register topics in advance, and there is no console screen where you create one.
Letting the user choose
The most common pattern is to tie a topic to a setting. When the user turns a switch on, subscribe. When they turn it off, unsubscribe. The widget below keeps the switch state in sync with the call result.
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
class NewsToggle extends StatefulWidget {
const NewsToggle({super.key});
@override
State<NewsToggle> createState() => _NewsToggleState();
}
class _NewsToggleState extends State<NewsToggle> {
bool _subscribed = false;
bool _busy = false;
Future<void> _onChanged(bool value) async {
setState(() => _busy = true);
try {
if (value) {
await FirebaseMessaging.instance.subscribeToTopic('news');
} else {
await FirebaseMessaging.instance.unsubscribeFromTopic('news');
}
if (mounted) setState(() => _subscribed = value);
} catch (e) {
debugPrint('Topic change failed: $e');
} finally {
if (mounted) setState(() => _busy = false);
}
}
@override
Widget build(BuildContext context) {
return SwitchListTile(
title: const Text('Breaking news'),
value: _subscribed,
onChanged: _busy ? null : _onChanged,
);
}
}This widget has a limit. The plugin has no method to ask which topics a device is subscribed to. The switch starts at false every time the widget is built, even if the device is subscribed. You must store the user's choice yourself, for example with shared_preferences, and read it back when the screen loads.
Sending to a topic
Sending uses the same HTTP v1 request shape as a single-device send. You replace the token field with topic. The two fields are mutually exclusive in one message.
{
"message": {
"topic": "news",
"notification": {
"title": "Breaking news",
"body": "A new story is available."
},
"data": {
"route": "/stories/123"
}
}
}You send this as a POST to https://fcm.googleapis.com/v1/projects/YOUR_PROJECT_ID/messages:send with an OAuth 2.0 access token in the Authorization: Bearer header. Data values must be strings, as with any other message.
You can also compose a topic message in the Firebase console. In the Messaging section, create a new notification and choose a topic as the target.
Combining topics with a condition
A condition sends to devices that match a boolean expression over topics. It uses && for "and", || for "or", and parentheses. You can combine up to five topics in one condition.
{
"message": {
"condition": "'sports' in topics && ('en' in topics || 'fr' in topics)",
"notification": {
"title": "Match tonight",
"body": "Kick-off at 20:00."
}
}
}This reaches devices subscribed to sports and to at least one of en or fr. Conditions are the usual way to target by language and interest at once without creating a topic for every combination.
Behavior of topic messages
Topic messages go through the same delivery path as token messages. The app-state rules from earlier chapters still apply:
| App state | Notification message | Data-only message |
|---|---|---|
| Foreground | Delivered to `onMessage`, no system banner | Delivered to `onMessage` |
| Background | System shows the banner. A tap fires `onMessageOpenedApp` | Delivered to the background handler |
| Terminated | System shows the banner. A tap is read with `getInitialMessage` | Delivered to the background handler, with platform limits |
Two differences matter for topics specifically.
First, delivery is not instant per device. FCM sends to a large fan-out in a distributed way, so devices receive the message over a span of time, not at the same moment. Do not rely on all devices showing the notification simultaneously.
Second, a send call returns a message ID, not a delivery count. Accepting the request tells you FCM took the message. It does not tell you how many devices received it. Use the delivery reports in the Firebase console to see aggregate results.
Limits and failure modes
- Subscription propagation delay. A new subscription can take a short time to become active. A message sent immediately after
subscribeToTopicreturns may miss that device. When you test, wait a bit between subscribing and sending. - One topic send is not private. Anyone's app can subscribe to any topic name, because the client call needs no server authorization. Never put sensitive or per-user content in a topic message. If the audience must be restricted, send to tokens from your server after checking each user's rights.
- Predictable names are guessable. A topic called
vip-customerscan be joined by a modified client. Treat topic membership as a preference, not as access control. - Throughput. Topic sends are designed for fan-out to many devices, but they are rate limited. A single project has a limit on the fan-out rate for topic messages. Very large audiences may be delivered slowly.
- Inactive tokens. FCM stops delivering to tokens that have been inactive for a long time, and those tokens eventually expire. Their topic subscriptions go with them.
- Subscription count. One app instance can subscribe to a limited number of topics, currently 2000. Design topics around real audience groups, not one topic per item.
Managing topics from a server
Client-side subscription is simple but has the weaknesses above. The Firebase Admin SDK can subscribe and unsubscribe a list of tokens on the server. This lets your backend decide who belongs to which topic after checking account data. It also lets you fix subscriptions in bulk, for example when you rename a topic. The Admin SDK is available for Node.js, Java, Python, Go and .NET.
The server approach needs you to store each user's token, which the token management chapter covers.
Choosing between a topic and a token
| Question | Use topics | Use tokens |
|---|---|---|
| Is the content the same for everyone in the group? | Yes | No |
| Does the message contain personal data? | No | Yes |
| Do you need to know each recipient? | No | Yes |
| Do you want to avoid storing tokens? | Yes | No |
| Do you need per-user delivery errors? | No | Yes |
Common errors
- Nothing arrives after subscribing. Check that the topic name matches exactly, including case. Confirm that the notification permission is granted and that you waited briefly after subscribing.
- Subscribe call throws. The device is likely offline, or Google Play services is missing on the emulator. Use an emulator image that includes Google Play.
- The switch resets after a restart. The plugin cannot report current subscriptions. Persist the user's choice yourself.
- A
/topics/newsname fails. The prefix is for the legacy API. Use the bare namenews.
Exercise
You build a settings screen with a "Match alerts" switch. Users report that after restarting the app the switch is always off, though they still receive alerts. Why does this happen, and how do you fix it? Also, would a topic be a good way to send "Your ticket for seat 14B is ready" to one fan?
Show answer
The plugin has no method to list a device's topic subscriptions, and the widget state resets to false on each build. The subscription stays active on FCM, so alerts keep arriving. Fix it by saving the user's choice (for example with shared_preferences) whenever subscribeToTopic or unsubscribeFromTopic succeeds, and reading it when the screen loads to set the switch. A topic is the wrong tool for the ticket message. It is personal and addressed to one person, and topic membership is not access controlled. Send it to that user's registration token from your server.
Exercise
Write the condition string that targets devices subscribed to football and to either de or es.
Show answer
'football' in topics && ('de' in topics || 'es' in topics)