You are currently viewing Flutter Firebase Cloud Messaging Examples

Flutter Firebase Cloud Messaging Examples

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably send messages at no cost.

Using FCM, you can notify a client app that new email or other data is available to sync. You can send notification messages to drive user re-engagement and retention. For use cases such as instant messaging, a message can transfer a payload of up to 4000 bytes to a client app.

Here are the key functionalities you get from Firebase Cloud Messaging:

  1. Ability to Send notification messages or data messages - You can Send notification messages that are displayed to your user. Or send data messages and determine completely what happens in your application code.
  2. Versatile message targeting - You can Distribute messages to your client app in any of 3 ways—to single devices, to groups of devices, or to devices subscribed to topics.
  3. Send messages from client apps - You can Send acknowledgments, chats, and other messages from devices back to your server over FCM’s reliable and battery-efficient connection channel.

How it Works.

An FCM implementation includes two main components for sending and receiving:

  1. A trusted environment such as Cloud Functions for Firebase or an app server on which to build, target, and send messages.
  2. An Apple, Android, or web (JavaScript) client app that receives messages via the corresponding platform-specific transport service.

You can read more here.

Let us look at some simple examples.

Example 1: Simple Firebase Push Notifications Example

A simple example to demonstrate push notifications in flutter using Firebase.

Step 1: Create Project

Start by creating an empty Android Studio project.

Step 2: Add Firebase to Project

If you do not know how to add firebase to your project then follow the instructions here.

Step 2: Dependencies

Go to your pubspec.yaml file and add firebase_analytics, firebase_messaging and firebase_core as dependencies as shown below:

dependencies:
  flutter:
    sdk: flutter
  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.0
  firebase_analytics: ^6.0.1
  firebase_messaging: ^7.0.2
  firebase_core: ^0.5.0

Then flutter pub get to fetch them.

Step 3: Write Code

Here is the full code:

main.dart

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Push Notification demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  String title = "Title will appear here";
  String messageData = "Message text will appear here";
  FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  @override
  void initState() {
    super.initState();
/*
Message that we are getting from firebase will be of form:-
  {
    notification:{
      title:'Custom Title that we send from firebase cloud messaging',
      body:'Text of the message will appear here'
    },
    data:{
      Here the extra data like if we include image,etc optional data from firebase cloud messaging
    }
  }
For sending Push notification go to Grow and then cloud messaging, from there send new message by adding title
and other fields as per requirement
*/
    // In Ios we need to request permission for sending Push notifcations but not in Android
    _firebaseMessaging.requestNotificationPermissions(
        const IosNotificationSettings(
            sound: true, badge: true, alert: true, provisional: true));
    _firebaseMessaging.configure(onMessage: (message) async {
      setState(() {
        print(message);
        title = message["notification"]["title"];
        messageData = message["notification"]["body"];
        notification(context, title, messageData);
      });
    }, onResume: (message) async {
      setState(() {
        print(message);
        title = message["notification"]["title"];
        messageData = message["notification"]["body"];
        notification(context, title, messageData);
      });
    }, onLaunch: (message) async {
      setState(() {
        print(message);
        title = message["notification"]["title"];
        messageData = message["notification"]["body"];
        notification(context, title, messageData);
      });
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Push Notification Demo'),
        backgroundColor: Colors.green,
        centerTitle: true,
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.only(top: 30.0),
          child: Column(
            children: <Widget>[
              Text(
                '$title',
                style: Theme.of(context).textTheme.headline4,
              ),
              SizedBox(height: 20.0,),
              Text(
                messageData,
                style: Theme.of(context).textTheme.headline6,
              ),
            ],
          ),
        ),
      ),
    );
  }
// this function will be called when a push notification is recieved and show as alert dialog along with
// title and message body
  Future notification(
      BuildContext context, String title, String messageText) async {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return AlertDialog(
            buttonPadding: EdgeInsets.all(10.0),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20.0)),
            title: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
                ),
                SizedBox(
                  height: 15.0,
                ),
                Text(
                  messageText,
                  style: TextStyle(fontSize: 16.0),
                )
              ],
            ),
            actions: [
              FlatButton(
                  onPressed: () => Navigator.pop(context), child: Text('Ok'))
            ],
          );
        });
  }
}

Run

Copy the code or download it in the link below, build and run.

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

Leave a Reply