Flutter Push Notifications using flutter firebase messaging with example

Published July 13, 2020


In this post we will learn how to implement firebase flutter push notifications service in flutter app

 

Flutter Firebase Push Notification

Step 1: Adding Firebase Messaging dependencies

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

 

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

dependencies:

firebase_messaging: ^6.0.16

 

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

Firebase Integration

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

Firebase Google Json file

Step 3: Add Firebase SDK

Open build-gradle ( project level )

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

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

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

 

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

Then, open build-gradle(app level)

project > Android > app > build-gradle

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)

 

Fiebase dependencies

step 4: 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>

 

Step 5: Create Model class 

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

 

 

Step 6: Update Dart file with below code

import 'package:flutter/material.dart';
import 'package:flutter_dialogratingbar/FirebaseMessage.dart';
import 'package:firebase_messaging/firebase_messaging.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 Pushnotification',
      theme: ThemeData(
       
        primarySwatch: Colors.blue,
      
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      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),
);

 

Step 7: 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

Pushnotification console

 


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1186 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions