Flutter Push Notifications using flutter firebase messaging with example
Flutter Push Notifications using flutter firebase messaging with example

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will learn how to implement firebase flutter push notifications service in flutter app.

Using which you can send Firebase Cloud messages to your flutter app user using firebase console that is flutter push notifications.

DEMO OUTPUT

flutter firebase push notification example
flutter firebase push notification example

Let’s start

Flutter Firebase Push Notification

Step 1: Adding Firebase Messaging dependencies

Using this Flutter Plugin we can use the Firebase Cloud Messaging  Service (FCM).

With the use of this plugin, your Flutter application will be ready to process and receive the push notification from the firebase console server as well as data messaging on android and iOS devices.

link to firebase messaging plugin here

Open pubspec.yaml file and under dependencies: line add this –

dependencies:
  firebase_messaging: ^6.0.13  // add this line

Step 2: Create a new project on firebase console

Open Firebase Console

1. Add / Create Project :

Give a name to your firebase project as “Firebase-Push-Notification”, Just fill all the common required details for creating the firebase project.

2. Add firebase to your android application

Then, After successful creating firebase project, you will see an Add app with list of platform where you can integrate firebase eg : android, iOS, web, unity3D.

Select Android playform

3. Register app with android package name

Came back to IDE (Android Studio)  Navigate towords Androidmanifest.xml file to get android package name

Flutter Project > Android > app > src > main > AndroidManifest.xml

Under this manifest file you will find package name copy it and paste it into firebase console as below screenshot.

Add Firebase to you flutter android app

adding firebase to your android app

Hit Next.

Add google-services.json Config file to your flutter android app

Download the firebase google-services.json file and paste it in your flutter project in android section.

download firebase project config json file

project > Android > app > (paste) google-services.json

adding google-services json

Add Firebase SDK

Open build-gradle ( project level )

futter project > Android > build-gradle(project level)

add this classpath:-

buildscript {
    repositories {
        google() // add this if not there
        jcenter()
    }

    dependencies {
       
        classpath 'com.google.gms:google-services:4.3.3' //add here line 
    }
}

as shown in the below screenshot

add firebase SDK build.gradle project level

Note: check if google() repositories is added, if not then add it

Then, open build-gradle(app level)

project > Android > app  > build-gradle

Add the google services apply plugin

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'   // add the plugin on top or at the bottom og build-gradle (app-level)

apply plugin google services

Step 3:  Add FLUTTER_NOTIFICATION_CLICK <intent-filter>

Open AndroidManifest.xml file and add the intent-filter

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

add flutter notification click intent filter in <activity tag as show in screenshot below

flutter notification click intent filter

Step 4: Create a directory DataModel and create a  datamodel class file

(right click) on lib > New > Package

Name the package as DataModel  under the directory create a new dart file named “FirebaseMessage.dart”

Then add the below lined of code in it.

import 'package:flutter/cupertino.dart';

class FirebaseMessage {
  final String title;
  final String body;

  const FirebaseMessage({@required this.title, @required this.body});
}

This class will hold the value received firebase cloud messaging services.

Step 5: Copy below code in main.dart file

main.dart

import 'package:flutter/material.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutterpushnotification/DataModel/FirebaseMessage.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  final List<FirebaseMessage> messageList = [];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _firebaseMessaging.configure(
        onResume: (Map<String, dynamic> message) async {
      print("on Resume : $message");
    }, onLaunch: (Map<String, dynamic> message) async {
      print("on Launch  : $message");
      final notification = message['notification'];
      setState(() {
        messageList.add(FirebaseMessage(
            title: notification['title'], body: notification['body']));
      });
    }, onMessage: (Map<String, dynamic> message) async {
      print("on Message : $message");
      final notification = message['notification'];
      setState(() {
        messageList.add(FirebaseMessage(
            title: notification['title'], body: notification['body']));
      });
    });
    _firebaseMessaging.requestNotificationPermissions(
      const IosNotificationSettings(sound: true, badge: true, alert: true),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Firebase Push Notification"),
      ),
      body: ListView(
        children: messageList.map(createListTile).toList(),
      ),
    );
  }
}

Widget createListTile(FirebaseMessage message) => ListTile(
      title: Text(message.title),
      subtitle: Text(message.body),
    );

There you go, our flutter app all is ready to receive message from firebase cloud messaging server.

Step 6 : Sending Push notification from firebase Console to your flutter project

Goto firebase console  to send push notification to your flutter project application.

On the left navigation bar Grow > Cloud Messaging

Click on send your first message

 

sending push notification flutter target

Do you remember? we have added <intent-filter> in our flutter AndroidManifest.xml

their we have have initial intent filter action as FLUTTER_NOTIFICATION_CLICK 

custom-data

key= click_action and value = FLUTTER_NOTIFICATION_CLICK

sending push notification additional optional

Then Click on Publish Button, then Firebase will send the push notifications to your flutter application as show in the above mobile screenshot.