Flutter Push Notification Example (using FCM)

flutter-push-notification-example

This tutorial, we're going to learn how to integrate push notification in your flutter apps. For that, we're going to use firebase messaging plugin https://github.com/flutter/plugins/tree/master/packages/firebase_messaging. Here I'm going to explain to you with step by step tutorial. If you're new to flutter, please visit Flutter Tutorial for more tutorials on flutter

Installation

First of all, we need to create a new project or we can use the existing project.we have to declare of dependencies inside pubspec.yaml

flutter create flutterfcm
cd flutterfcm

Then open your pubspec.yaml file, then add

dependencies:
  flutter:

    sdk: flutter

  firebase_messaging: ^5.0.4

Once, we have done with dependencies, we must edit our package name in order to work with firebase push notification

Working with the Android Project File

  • Working with android/app/src/build.gradle file

    • Navigate to your android/app/src/build.gradle
    • Update your package name from defaultConfig -> applicationId
    • After updating the package name, we need to add google-service inside your apply plugin: 'com.google.gms.google-services'
  • Working with android/build.gradle file

    • Open android/app/build.gradle & add classpath for google-service classpath 'com.google.gms:google-services:4.2.0'
  • Working with AndroidManifest.xml

    • Open android/app/src/main/AndroidManifest.xml
    <intent-filter>
     <action android:name="FLUTTER_NOTIFICATION_CLICK"/>
     <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>

add these lines inside <activity>

  • Copy & Paste your google-service.json file

    • Download google-service.json file from firebase (mentioned on next step) & paste android/app/ folder

Working with Firebase

  • Login to your firebase account & create a new project or choose an existing project
  • Navigate to Project Overview > Project Settings
  • Add your support Email then
  • scroll down then click Add Android App
  • Fill your package name, nickname and SHA-1 Key (Refer: https://developers.google.com/android/guides/client-auth)
  • Click Next & download google-service.json
  • Copy google-service.json & paste android/app/ as mentioned on previous steps

Working with Flutter Push Notification

Now, we have completed all of our configurations, we now can write code to receive notification.copy below code and paste it on your main.dart. I have explained code below

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

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  String _message = '';

  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

  _register() {
    _firebaseMessaging.getToken().then((token) => print(token));
  }

  
  void initState() {
    // TODO: implement initState
    super.initState();
    getMessage();
  }
  
  void getMessage(){
    _firebaseMessaging.configure(
        onMessage: (Map<String, dynamic> message) async {
      print('on message $message');
      setState(() => _message = message["notification"]["title"]);
    }, onResume: (Map<String, dynamic> message) async {
      print('on resume $message');
      setState(() => _message = message["notification"]["title"]);
    }, onLaunch: (Map<String, dynamic> message) async {
      print('on launch $message');
      setState(() => _message = message["notification"]["title"]);
    });
  }

  
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text("Message: $_message"),
            OutlineButton(
              child: Text("Register My Device"),
              onPressed: () {
                _register();
              },
            ),
            // Text("Message: $message")
          ]),
        ),
      ),
    );
  }
}

Code Explanation

  • We created a stateful widget, because, we're displaying message dynamically whenever new message arrived.
  • We have created an instance called _firebaseMessaging using FirebaseMessaging()
  • using _firebaseMessaging.getToken() we're registering our app with firebase & Received token
  • _firebaseMessaging.configure() allows as to create some action based on the received message, such as onMessage, onResume, onLaunch
  • We simply use setState to display the current message on the screen

Sending Push Notification

If you want to send a push notification, we can use the firebase console to send a message.we also can use the terminal to testing purpose (CURL must be enabled)

  • To get server key, please navigate to firebase Project Overview -> Project Settings -> Cloud Messaging & copy server key
  • You can copy device token from your terminal

    DATA='{"notification": {"body": "this is a body", "title": "this is a title"}, "priority": "high", "data": {"clickaction": "FLUTTERNOTIFICATIONCLICK", "id": "1", "status": "done"}, "to": "ccbTAyu9GTM: APA91bFb58HWa3d73BjS9oBk6pWkR1XpYiJiFXwBf-OGgu3QItVyPR-sZ1WRhE2WaGWIRMHw0yIXeEJFq-3WdnhxE1GkGRvlev56faOAQKfEjGeD8H9FvNGyPHUrb"}' curl https://fcm.googleapis.com/fcm/send -H "Content-Type:application/json" -X POST -d "$DATA" -H "Authorization: key=AAAARx2WWw4: APA91bFRCwWXKNSTSTdYznuIflRijbS03V8qzj8RvDN7vv22Xw8Km3dCIfEYliBXhb9b8yF5mlnBS7jHJkKfyxfmERaTttzI9lZyIxED3Psid14v_XELvZO5yBUTB2U-W"

Note: Please update your own server key and FCM Token