FirebaseCloudMessagingServer class

A server-side client for sending Firebase Cloud Messages via the FCM HTTP v1 API directly from Dart or Flutter.

The default base endpoint used is _fcmApiEndpoint.

Quick start

import 'dart:convert';
import 'dart:io';
import 'package:firebase_cloud_messaging_flutter/firebase_cloud_messaging_flutter.dart';

void main() async {
  final credentials = jsonDecode(
    File('service_account.json').readAsStringSync(),
  ) as Map<String, dynamic>;

  final server = FirebaseCloudMessagingServer(credentials);

  final result = await server.send(
    FirebaseSend(
      message: FirebaseMessage(
        token: '<device-token>',
        notification: FirebaseNotification(
          title: 'Hello!',
          body: 'Message from the server.',
        ),
      ),
    ),
  );

  print(result);
  server.dispose(); // Always dispose when done.
}

Authentication

FirebaseCloudMessagingServer authenticates with FCM using a Google Service Account. Open Firebase Console → Settings → Service Accounts → Generate new private key and pass the contents of the downloaded JSON file to this constructor.

Caching & disposal

By default (cacheAuth = true) the OAuth 2.0 access token is reused until it expires (≈1 hour), then refreshed automatically. Call dispose when you are done with the server to close the underlying HTTP client.

Constructors

FirebaseCloudMessagingServer(Map<String, dynamic>? firebaseServiceCredentials, {String? projectId, bool cacheAuth = true, FcmLogger logger = fcmSilentLogger, FcmRetryConfig retryConfig = const FcmRetryConfig(), FcmRegistrationCallback? onRegistrationChange, Client? httpClient})
Creates a server instance from a pre-parsed service-account Map.
FirebaseCloudMessagingServer.applicationDefault({required String projectId, bool cacheAuth = true, FcmLogger? logger, FcmRetryConfig retryConfig = const FcmRetryConfig(), FcmRegistrationCallback? onRegistrationChange, Client? httpClient})
Creates a server instance that authenticates using Google Application Default Credentials (ADC).
factory
FirebaseCloudMessagingServer.fromServiceAccountFile(Object serviceAccountFile, {bool cacheAuth = true, FcmLogger? logger, FcmRetryConfig retryConfig = const FcmRetryConfig(), FcmRegistrationCallback? onRegistrationChange, Client? httpClient})
Creates a server instance by reading a service-account JSON file.
factory
FirebaseCloudMessagingServer.fromServiceAccountJson(String jsonString, {bool cacheAuth = true, FcmLogger? logger, FcmRetryConfig retryConfig = const FcmRetryConfig(), FcmRegistrationCallback? onRegistrationChange, Client? httpClient})
Creates a server instance from a service-account JSON String.
factory

Properties

cacheAuth bool
When true (default), the OAuth access token is cached and reused until it expires. Set to false to force a fresh token on every request.
final
firebaseServiceCredentials Map<String, dynamic>?
The endpoint for the IID batch registration API (Subscribe). The endpoint for the IID batch registration API (Unsubscribe). The service account credentials loaded from Firebase Console.
final
hashCode int
The hash code for this object.
no setterinherited
logger FcmLogger
Optional logger for diagnostic output.
final
onRegistrationChange FcmRegistrationCallback?
Optional callback triggered when a token registration becomes invalid.
final
retryConfig FcmRetryConfig
Controls automatic retry for retryable FCM errors (QUOTA_EXCEEDED and UNAVAILABLE).
final
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

dispose() → void
Closes the underlying HTTP client and releases resources.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
performAuth() Future<AccessCredentials>
Fetches a fresh OAuth 2.0 access token from Google and caches it.
send(FirebaseSend sendObject) Future<ServerResult>
Sends a single FCM message.
sendMessages(List<FirebaseSend> sendObjects) Future<List<ServerResult>>
Sends multiple pre-built FirebaseSend objects sequentially.
sendToCondition(String condition, FirebaseMessage message) Future<ServerResult>
Convenience method to send a message to devices matching a condition.
sendToMultiple({required List<String> tokens, required FirebaseMessage messageTemplate, bool validateOnly = false}) Future<BatchResult>
Sends the same notification to tokens in parallel and returns an aggregated BatchResult.
sendToTopic(String topic, FirebaseMessage message) Future<ServerResult>
Convenience method to send a message to an FCM topic.
subscribeTokensToTopic({required String topic, required List<String> tokens}) Future<TopicManagementResult>
Subscribes a list of registration tokens to an FCM topic.
toString() String
A string representation of this object.
inherited
unsubscribeTokensFromTopic({required String topic, required List<String> tokens}) Future<TopicManagementResult>
Unsubscribes a list of registration tokens from an FCM topic.
validateMessage(FirebaseSend sendObject) Future<ServerResult>
Validates a message payload without actually delivering it.

Operators

operator ==(Object other) bool
The equality operator.
inherited