firebase_messaging 2.0.3

  • Readme
  • Changelog
  • Example
  • Installing
  • 85

Firebase Cloud Messaging for Flutter #

pub package

A Flutter plugin to use the Firebase Cloud Messaging (FCM) API.

With this plugin, your Flutter app can receive and process push notifications as well as data messages on Android and iOS. Read Firebase's About FCM Messages to learn more about the differences between notification messages and data messages.

For Flutter plugins for other Firebase products, see

Note: This plugin is still under development, and some APIs might not be available yet. Feedback and Pull Requests are most welcome!

Usage #

To use this plugin, add firebase_messaging as a dependency in your pubspec.yaml file.

Getting Started #

Check out the example directory for a sample app using Firebase Cloud Messaging.

Android Integration #

To integrate your plugin into the Android part of your app, follow these steps:

  1. Using the Firebase Console add an Android app to your project: Follow the assistant, download the generated google-services.json file and place it inside android/app. Next, modify the android/build.gradle file and the android/app/build.gradle file to add the Google services plugin as described by the Firebase assistant.

  2. (optional, but recommended) If want to be notified in your app (via onResume and onLaunch, see below) when the user clicks on a notification in the system tray include the following intent-filter within the <activity> tag of your android/app/src/main/AndroidManifest.xml:

      <action android:name="FLUTTER_NOTIFICATION_CLICK" />
      <category android:name="android.intent.category.DEFAULT" />

iOS Integration #

To integrate your plugin into the iOS part of your app, follow these steps:

  1. Generate the certificates required by Apple for receiving push notifications following this guide in the Firebase docs. You can skip the section titled "Create the Provisioning Profile".

  2. Using the Firebase Console add an iOS app to your project: Follow the assistant, download the generated GoogleService-Info.plist file, open ios/Runner.xcworkspace with Xcode, and within Xcode place the file inside ios/Runner. Don't follow the steps named "Add Firebase SDK" and "Add initialization code" in the Firebase assistant.

  3. In Xcode, select Runner in the Project Navigator. In the Capabilities Tab turn on Push Notifications.

  4. Remove the use_frameworks! line from ios/Podfile (workaround for flutter/flutter#9694).

  5. Follow the steps in the "Upload your APNs certificate" section of the Firebase docs.

Dart/Flutter Integration #

From your Dart code, you need to import the plugin and instantiate it:

import 'package:firebase_messaging/firebase_messaging.dart';

final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

Next, you should probably request permissions for receiving Push Notifications. For this, call _firebaseMessaging.requestNotificationPermissions(). This will bring up a permissions dialog for the user to confirm on iOS. It's a no-op on Android. Last, but not least, register onMessage, onResume, and onLaunch callbacks via _firebaseMessaging.configure() to listen for incoming messages (see table below for more information).

Receiving Messages #

Messages are sent to your Flutter app via the onMessage, onLaunch, and onResume callbacks that you configured with the plugin during setup. Here is how different message types are delivered on the supported platforms:

App in ForegroundApp in BackgroundApp Terminated
Notification on AndroidonMessageNotification is delivered to system tray. When the user clicks on it to open app onResume fires if click_action: FLUTTER_NOTIFICATION_CLICK is set (see below).Notification is delivered to system tray. When the user clicks on it to open app onLaunch fires if click_action: FLUTTER_NOTIFICATION_CLICK is set (see below).
Notification on iOSonMessageNotification is delivered to system tray. When the user clicks on it to open app onResume fires.Notification is delivered to system tray. When the user clicks on it to open app onLaunch fires.
Data Message on AndroidonMessageonMessage while app stays in the background.not supported by plugin, message is lost
Data Message on iOSonMessageMessage is stored by FCM and delivered to app via onMessage when the app is brought back to foreground.Message is stored by FCM and delivered to app via onMessage when the app is brought back to foreground.

Additional reading: Firebase's About FCM Messages.

Sending Messages #

Refer to the Firebase documentation about FCM for all the details about sending messages to your app. When sending a notification message to an Android device, you need to make sure to set the click_action property of the message to FLUTTER_NOTIFICATION_CLICK. Otherwise the plugin will be unable to deliver the notification to your app when the users clicks on it in the system tray.

For testing purposes, the simplest way to send a notification is via the Firebase Console. Make sure to include click_action: FLUTTER_NOTIFICATION_CLICK as a "Custom data" key-value-pair (under "Advanced options") when targeting an Android device. The Firebase Console does not support sending data messages.

Alternatively, a notification or data message can be sent from a terminal:

DATA='{"notification": {"body": "this is a body","title": "this is a title"}, "priority": "high", "data": {"click_action": "FLUTTER_NOTIFICATION_CLICK", "id": "1", "status": "done"}, "to": "<FCM TOKEN>"}'
curl -H "Content-Type:application/json" -X POST -d "$DATA" -H "Authorization: key=<FCM SERVER KEY>"

Remove the notification property in DATA to send a data message.

2.0.3 #

  • Removing local cache of getToken() in the dart part of the plugin. Now getToken() calls directly its counterparts in the iOS and Android implementations. This enables obtaining its value without calling configure() or having to wait for a new token refresh.

2.0.2 #

  • Use boolean values when checking for notification types on iOS.

2.0.1 #

  • Bump Android dependencies to latest.

2.0.0 #

  • Updated Android to send Remote Message's title and body to Dart.

1.0.5 #

  • Bumped test and mockito versions to pick up Dart 2 support.

1.0.4 #

  • Bump Android and Firebase dependency versions.

1.0.3 #

  • Updated iOS token hook from 'didRefreshRegistrationToken' to 'didReceiveRegistrationToken'

1.0.2 #

  • Updated Gradle tooling to match Android Studio 3.1.2.

1.0.1 #

  • Fix for Android where the onLaunch event is not triggered when the Activity is killed by the OS (or if the Don't keep activities toggle is enabled)

1.0.0 #

  • Bump to released version

0.2.5 #

  • Fixed Dart 2 type error.

0.2.4 #

  • Updated Google Play Services dependencies to version 15.0.0.

0.2.3 #

  • Updated package channel name

0.2.2 #

  • Simplified podspec for Cocoapods 1.5.0, avoiding link issues in app archives.

0.2.1 #

  • Fixed Dart 2 type errors.

0.2.0 #

  • Breaking change. Set SDK constraints to match the Flutter beta release.

0.1.4 #

  • Fixed Dart 2 type error in example project.

0.1.3 #

  • Enabled use in Swift projects.

0.1.2 #

  • Fix for APNS not being correctly registered on iOS when reinstalling application.

0.1.1 #

  • Simplified and upgraded Android project template to Android SDK 27.
  • Updated package description.

0.1.0 #

  • Breaking change. Upgraded to Gradle 4.1 and Android Studio Gradle plugin 3.0.1. Older Flutter projects need to upgrade their Gradle setup as well in order to use this version of the plugin. Instructions can be found here.
  • Relaxed GMS dependency to [11.4.0,12.0[

0.0.8 #

  • Added FLT prefix to iOS types
  • Change GMS dependency to 11.4.+

0.0.7 #

In FirebaseMessagingPlugin.m:

  • moved logic from 'tokenRefreshNotification' to 'didRefreshRegistrationToken'
  • removed 'tokenRefreshNotification' as well as observer registration
  • removed 'connectToFcm' method and related calls
  • removed unnecessary FIRMessaging disconnect

0.0.6 #

  • Change GMS dependency to 11.+

0.0.5+2 #

  • Fixed README example for "click_action"

0.0.5+1 #

  • Aligned author name with rest of repo.

0.0.5 #

  • Updated to Firebase SDK to always use latest patch version for 11.0.x builds

0.0.4 #

  • Updated to Firebase SDK Version 11.0.1

0.0.3 #

  • Updated
  • Bumped buildToolsVersion to 25.0.3

0.0.2+2 #

  • Updated

0.0.2+1 #

0.0.2 #

  • Updated to latest plugin API

0.0.1+2 #

  • Downgraded gradle dependency for example app to make flutter run happy

0.0.1+1 #

  • Updated README with installation instructions

0.0.1 #

  • Initial Release


// Copyright 2017 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

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

final Map<String, Item> _items = <String, Item>{};
Item _itemForMessage(Map<String, dynamic> message) {
  final String itemId = message['data']['id'];
  final Item item = _items.putIfAbsent(itemId, () => Item(itemId: itemId))
    ..status = message['data']['status'];
  return item;

class Item {
  final String itemId;

  StreamController<Item> _controller = StreamController<Item>.broadcast();
  Stream<Item> get onChanged =>;

  String _status;
  String get status => _status;
  set status(String value) {
    _status = value;

  static final Map<String, Route<void>> routes = <String, Route<void>>{};
  Route<void> get route {
    final String routeName = '/detail/$itemId';
    return routes.putIfAbsent(
      () => MaterialPageRoute<void>(
            settings: RouteSettings(name: routeName),
            builder: (BuildContext context) => DetailPage(itemId),

class DetailPage extends StatefulWidget {
  final String itemId;
  _DetailPageState createState() => _DetailPageState();

class _DetailPageState extends State<DetailPage> {
  Item _item;
  StreamSubscription<Item> _subscription;

  void initState() {
    _item = _items[widget.itemId];
    _subscription = _item.onChanged.listen((Item item) {
      if (!mounted) {
      } else {
        setState(() {
          _item = item;

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Item ${_item.itemId}"),
      body: Material(
        child: Center(child: Text("Item status: ${_item.status}")),

class PushMessagingExample extends StatefulWidget {
  _PushMessagingExampleState createState() => _PushMessagingExampleState();

class _PushMessagingExampleState extends State<PushMessagingExample> {
  String _homeScreenText = "Waiting for token...";
  bool _topicButtonsDisabled = false;

  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  final TextEditingController _topicController =
      TextEditingController(text: 'topic');

  Widget _buildDialog(BuildContext context, Item item) {
    return AlertDialog(
      content: Text("Item ${item.itemId} has been updated"),
      actions: <Widget>[
          child: const Text('CLOSE'),
          onPressed: () {
            Navigator.pop(context, false);
          child: const Text('SHOW'),
          onPressed: () {
            Navigator.pop(context, true);

  void _showItemDialog(Map<String, dynamic> message) {
      context: context,
      builder: (_) => _buildDialog(context, _itemForMessage(message)),
    ).then((bool shouldNavigate) {
      if (shouldNavigate == true) {

  void _navigateToItemDetail(Map<String, dynamic> message) {
    final Item item = _itemForMessage(message);
    // Clear away dialogs
    Navigator.popUntil(context, (Route<dynamic> route) => route is PageRoute);
    if (!item.route.isCurrent) {
      Navigator.push(context, item.route);

  void initState() {
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
        const IosNotificationSettings(sound: true, badge: true, alert: true));
        .listen((IosNotificationSettings settings) {
      print("Settings registered: $settings");
    _firebaseMessaging.getToken().then((String token) {
      assert(token != null);
      setState(() {
        _homeScreenText = "Push Messaging token: $token";

  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Push Messaging Demo'),
        // For testing -- simulate a message being received
        floatingActionButton: FloatingActionButton(
          onPressed: () => _showItemDialog(<String, dynamic>{
                "id": "2",
                "status": "out of stock",
          tooltip: 'Simulate Message',
          child: const Icon(Icons.message),
        body: Material(
          child: Column(
            children: <Widget>[
                child: Text(_homeScreenText),
              Row(children: <Widget>[
                  child: TextField(
                      controller: _topicController,
                      onChanged: (String v) {
                        setState(() {
                          _topicButtonsDisabled = v.isEmpty;
                  child: const Text("subscribe"),
                  onPressed: _topicButtonsDisabled
                      ? null
                      : () {
                  child: const Text("unsubscribe"),
                  onPressed: _topicButtonsDisabled
                      ? null
                      : () {

  void _clearTopicText() {
    setState(() {
      _topicController.text = "";
      _topicButtonsDisabled = true;

void main() {
      home: PushMessagingExample(),

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:

  firebase_messaging: ^2.0.3

2. Install it

You can install packages from the command line:

with Flutter:

$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:

import 'package:firebase_messaging/firebase_messaging.dart';
Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

We analyzed this package on May 16, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.1
  • pana: 0.13.8-dev
  • Flutter: 1.17.0

Maintenance issues and suggestions

Homepage URL doesn't exist. (-20 points)

At the time of the analysis the homepage field was unreachable.

Package is getting outdated. (-54.52 points)

The package was last published 80 weeks ago.


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.28.0 <3.0.0
flutter 0.0.0
meta ^1.0.4 1.1.8
platform ^2.0.0 2.2.1
Transitive dependencies
collection 1.14.12
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
firebase_core ^0.2.5+1
mockito ^3.0.0
test ^1.3.0