Categories
Flutter

Push Notification in Flutter using Firebase

In this article, you will learn about how to integrate Firebase Cloud Messaging (FCM) with a Flutter mobile application.

If you want to install Flutter in your environment follow this article: Flutter Setup

Create Flutter project

To create a new project in Flutter execute the following command line in the terminal.

flutter create tryoutflutter

We are using tryoutflutter as the project name. It will create a folder with the name of the project. Inside the project, the files structure should like this:

Let’s look at the folders and files in the project.

android folder: this includes specific files to configure our Android application.

  • To get special permissions,
  • Firebase configuration,
  • To set a logo, splash screen, display name, etc,.

iOS folder, this includes specific files to configure our iOS application.

Build folder, this includes the debug application build APK. This will automatically create once you run the project.

lib folder, this includes Dart files. In this folder, we need to write and manage Dart code.

pubspec.yaml, in this file we can manage the packages (libraries), assets (images, icons, etc,.) that we will use for our application.

Create Firebase Project

Follow the steps to create a new firebase project,

  • Goto Firebase and login with your Google account
  • Then navigate to the Firebase console in that you can create a project
  • Give a name to your project. If you want Google Analytics for your project, enable it otherwise it’s optional only. Wait for a moment once your project is ready, we can start setup.

Android setup

  • Open your Firebase project, click the Android icon or add app button, it will return a form. Fill out the form to register the app.
  • To know the package name of your application look into the androidmanifest.xml or app level build.gradle file
Paste the file in this location PATH: <projectname>/android/app/’Paste the file here’
  • Firebase returns a config file in JSON format. Download and place in your project folder, in the following path <projectName>/android/app.
  • Click the next button. Then add Firebase SDK by following the Firebase assistant.
  • Add this dependency implementation 'com.google.firebase:firebase-messaging:' in your app level build.gradle file, to enable receive messages in the background. Check this link to get the latest version.

iOS setup

  • Open your Firebase project, click the iOS button or add app button, it will return a form. Fill out the form to register the app.
  • To know the app bundle id, open your project in Xcode. Select runner in file navigator and select runner in the target also. Copy the bundle id from the identity section.
To know Bundle id from Xcode
  • Now you have registered your app in Firebase, then skip the upcoming steps. That’s only required if you use native development.

Follow the steps to enable APN’s:

  • To send push notification to iOS devices have to enable the Apple Push Notification service to setup that follow this documentation,
  • After the creation of an identifier key and a provisioning profile in your developer account, add your team id in Firebase iOS Flutter project settings.
  • Download the latest config file. Place the file in your Flutter project folder, in the following path <project name>/ios/Runner.xcworkspace
  • Open the project in Xcode, select Runner in the project navigator. Select capability add following capabilities, Push notifications and background modes.
  • Also enable background fetch and remote notifications under the background modes.

Compose notification

Android setup is done, if you send any notification from Firebase Cloud Messaging (FCM), the devices will be able to receive for (Android only). For iOS only we need to get the permissions, refer to the code attached below.

Let see how to compose notification to send,

  • Navigate to Cloud Messaging in your Firebase project, then Click the new notification.
  • Give the title and select the target applications.
  • Click the review button, and publish the notification. It will send a notification to all devices.

Configuring FCM

Let see how to send a notification to a specific device and to a group of devices which is subscribed to a topic.

Now it’s time to code, add this package firebase_messaging: in pubspec.yaml file under the dependencies.

To receive notification in device

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

//A statefull widget
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final FirebaseMessaging _fcm = FirebaseMessaging(); // Here _fcm is instance of FirebaseMessaging 
  @override
  void initState() {
    super.initState();
    if (Platform.isIOS) {
      _fcm.requestNotificationPermissions(IosNotificationSettings()); //Geting permission for iOS only
    }
    _fcm.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message"); //It fires when the app is open, if notification received
      },
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message"); //If notification received, it fires when app is running in backgroud
      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message"); // If notification received, it fires when app is fully terminated
      },
    ); //With 
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Container()
    );
  }
}

Send notification to a topic

It’s simple, we have to configure in both composing the notification as well as also while receiving the notification in the device.

Type your topic name in the message topic field, with this reference it will send the notification to all subscribed devices.

Subscribe to an topic

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

//A statefull widget
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final FirebaseMessaging _fcm = FirebaseMessaging(); // Here _fcm is instance of FirebaseMessaging 
  @override
  void initState() {
    super.initState();
    if (Platform.isIOS) {
      _fcm.requestNotificationPermissions(IosNotificationSettings()); //Geting permission for iOS only
    }
    _fcm.subscribeToTopic('topic'); // Topic subscribed
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Container()
    );
  }
}

Send notification to a specific device

FCM provides unique tokens to all devices, the code below will show how to get the device token.

getToken() async {
    //print(await _fcm.getToken());
    //The getToken() will return a Future string, so async is used 
    return await _fcm.getToken(); 
  }

We need to set up a server to send a notification to specific devices, store the device token in the database, and use it with your logic. Refer to this documentation for more detail about the setup.

To send dynamic notification using FCM, have to go for Firebase Cloud functions.

I have attached the complete code in this GitHub repo.

Leave a Reply

Your email address will not be published. Required fields are marked *