Flutter Push Notification Tutorial

flutter-firebase-push-notification-tutorial-example
flutter-firebase-push-notification-tutorial-example

This tutorial, we’re going to learn how to integrate push notification in your flutter apps. For that, we’re going to use a firebase messaging plugin http://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
<span class="hljs-built_in">cd</span> flutterfcm

Then open your pubspec.yaml file, then add

<span class="hljs-symbol">dependencies:</span>
<span class="hljs-symbol">  flutter:</span>
<span class="hljs-symbol">
    sdk:</span> flutter
<span class="hljs-symbol">
  firebase_messaging:</span> ^<span class="hljs-number">5.0</span><span class="hljs-number">.4</span>

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
      <span class="hljs-tag"><<span class="hljs-name">intent-filter</span>></span>
       <span class="hljs-tag"><<span class="hljs-name">action</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"FLUTTER_NOTIFICATION_CLICK"</span>/></span>
       <span class="hljs-tag"><<span class="hljs-name">category</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"android.intent.category.DEFAULT"</span>/></span>
      <span class="hljs-tag"></<span class="hljs-name">intent-filter</span>></span>
      

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: http://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

<span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/material.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:firebase_messaging/firebase_messaging.dart'</span>;

<span class="hljs-keyword">void</span> main() => runApp(MyApp());

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyApp</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatefulWidget</span> </span>{
  <span class="hljs-meta">@override</span>
  State<StatefulWidget> createState() {
    <span class="hljs-keyword">return</span> _MyAppState();
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">_MyAppState</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">State</span><<span class="hljs-title">MyApp</span>> </span>{
  <span class="hljs-built_in">String</span> _message = <span class="hljs-string">''</span>;

  <span class="hljs-keyword">final</span> FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

  _register() {
    _firebaseMessaging.getToken().then((token) => <span class="hljs-built_in">print</span>(token));
  }

  <span class="hljs-meta">@override</span>
  <span class="hljs-keyword">void</span> initState() {
    <span class="hljs-comment">// <span class="hljs-doctag">TODO:</span> implement initState</span>
    <span class="hljs-keyword">super</span>.initState();
    getMessage();
  }

  <span class="hljs-keyword">void</span> getMessage(){
    _firebaseMessaging.configure(
        onMessage: (<span class="hljs-built_in">Map</span><<span class="hljs-built_in">String</span>, <span class="hljs-keyword">dynamic</span>> message) <span class="hljs-keyword">async</span> {
      <span class="hljs-built_in">print</span>(<span class="hljs-string">'on message $message'</span>);
      setState(() => _message = message[<span class="hljs-string">"notification"</span>][<span class="hljs-string">"title"</span>]);
    }, onResume: (<span class="hljs-built_in">Map</span><<span class="hljs-built_in">String</span>, <span class="hljs-keyword">dynamic</span>> message) <span class="hljs-keyword">async</span> {
      <span class="hljs-built_in">print</span>(<span class="hljs-string">'on resume $message'</span>);
      setState(() => _message = message[<span class="hljs-string">"notification"</span>][<span class="hljs-string">"title"</span>]);
    }, onLaunch: (<span class="hljs-built_in">Map</span><<span class="hljs-built_in">String</span>, <span class="hljs-keyword">dynamic</span>> message) <span class="hljs-keyword">async</span> {
      <span class="hljs-built_in">print</span>(<span class="hljs-string">'on launch $message'</span>);
      setState(() => _message = message[<span class="hljs-string">"notification"</span>][<span class="hljs-string">"title"</span>]);
    });
  }

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-comment">// <span class="hljs-doctag">TODO:</span> implement build</span>
    <span class="hljs-keyword">return</span> MaterialApp(
      home: Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(<span class="hljs-string">"Message: $_message"</span>),
            OutlineButton(
              child: Text(<span class="hljs-string">"Register My Device"</span>),
              onPressed: () {
                _register();
              },
            ),
            <span class="hljs-comment">// Text("Message: $message")</span>
          ]),
        ),
      ),
    );
  }
}

Code Explanation

  • We created a stateful widget, because, we’re displaying messages dynamically whenever new messages 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='{<span class="hljs-string">"notification"</span>: {<span class="hljs-string">"body"</span>: <span class="hljs-string">"this is a body"</span>, <span class="hljs-string">"title"</span>: <span class="hljs-string">"this is a title"</span>}, <span class="hljs-string">"priority"</span>: <span class="hljs-string">"high"</span>, <span class="hljs-string">"data"</span>: {<span class="hljs-string">"click_action"</span>: <span class="hljs-string">"FLUTTER_NOTIFICATION_CLICK"</span>, <span class="hljs-string">"id"</span>: <span class="hljs-string">"1"</span>, <span class="hljs-string">"status"</span>: <span class="hljs-string">"done"</span>}, <span class="hljs-string">"to"</span>: <span class="hljs-string">"ccbTAyu9GTM: APA91bFb58HWa3d73BjS9oBk6pWkR1XpYiJiFXwBf-OGgu3QItVyPR-sZ1_WRhE2WaGW_IRMHw_0yIXeEJFq-3WdnhxE1GkGRvlev56faOAQKfEjGe_D8H_9FvNGyPHUrb"</span>}'
curl http://fcm.googleapis.com/fcm/send -H <span class="hljs-string">"Content-Type:application/json"</span> -X POST -d <span class="hljs-string">"<span class="hljs-variable">$DATA</span>"</span> -H <span class="hljs-string">"Authorization: key=AAAARx2WWw4: APA91bFRCwWXKNSTSTdYznuIflRijbS03V8qzj8RvDN7vv22Xw8Km3dCIfEYliBXhb9b8yF_5mlnBS7jHJkKfyxfmERaTttzI9lZyIxED3Psi_d14v_XELvZO5yBUTB2U-W"</span>

Note: Please update your own server key and FCM Token