firebase_messaging 0.0.1

Firebase Cloud Messaging for Flutter #

Build Status

WARNING: This is incomplete and experimental.

This plugin allows Flutter apps to interact with the Firebase Cloud Messaging (FCM) API from Dart code.

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.

Not all features of the API are implemented in the plugin yet. If something is missing feel free to send a pull request or file an issue.

Getting Started #

Check out the example directory for a sample app that uses this plugin. To learn more about Flutter plugins in general, view our online documentation.

TODO(goderbauer): Add Step-by-step instructions for integrating the plugin into an app.

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": {"click_action": "FLUTTER_NOTIFICATION_CLICK", "body": "this is a body","title": "this is a title"}, "priority": "high", "data": {"id": "1", "status": "done"}, "to": "<FCM TOKEN>"}'
curl https://fcm.googleapis.com/fcm/send -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.

example/lib/main.dart

// 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) {
  String itemId = message['id'];
  Item item = _items.putIfAbsent(itemId, () => new Item(itemId: itemId))
    ..status = message['status'];
  return item;
}

class Item {
  Item({this.itemId});
  final String itemId;

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

  String _status;
  String get status => _status;
  set status(String value) {
    _status = value;
    _controller.add(this);
  }

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

class DetailPage extends StatefulWidget {
  DetailPage(this.itemId);
  final String itemId;
  @override
  _DetailPageState createState() => new _DetailPageState();
}

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

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

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

class PushMessagingExample extends StatefulWidget {
  @override
  _PushMessagingExampleState createState() => new _PushMessagingExampleState();
}

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

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

  Future<Null> _showItemDialog(Map<String, dynamic> message) async {
    Item item = _itemForMessage(message);
    showDialog(
        context: context,
        child: new AlertDialog(
          content: new Text("Item ${item.itemId} has been updated"),
          actions: <Widget>[
            new FlatButton(
                child: new Text('CLOSE'),
                onPressed: () {
                  Navigator.pop(context, false);
                }),
            new FlatButton(
                child: new Text('SHOW'),
                onPressed: () {
                  Navigator.pop(context, true);
                }),
          ],
        )).then((bool shouldNavigate) {
      if (shouldNavigate == true) _navigateToItemDetail(message);
    });
  }

  Future<Null> _navigateToItemDetail(Map<String, dynamic> message) async {
    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);
  }

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

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

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

void main() {
  runApp(
    new MaterialApp(
      home: new PushMessagingExample(),
    ),
  );
}

Use this package as a library

1. Depend on it

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


dependencies:
  firebase_messaging: ^0.0.1

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or 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';
  
Awaiting analysis to complete.