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.

Categories
Flutter

Flutter Setup

HelloWorld! In this article, you will learn about how to setup Flutter in Windows, Linux, and Mac OS through step by step simple procedure. Let’s get started,

Prerequisites

  • Android Studio
  • X Code and CocoaPods only for Mac OS
  • VS Code editor or any other editor. VS code editor is recommended because it has the Flutter plugin which helps in fast debugging
  • Git version control
  • Install Flutter and Dart plugin in Android studio.

Setup for Windows

Minimum requirements

  • Require at least Windows 7 SP1 or later
  • Disk space around 1.3 GB required only for flutter setup
  • Flutter depends on Windows PowerShell 5.0 or newer (this is pre-installed with windows 10), if your using windows 10 don’t worry about it and if you want to clone the GitHub repository have to install Git

To download Git for Windows x86 and Windows x64.

Download and setup Flutter

  • Download the Flutter SDK from this link or clone the Flutter’s repository by executing the following command in your terminal,
git clone https://github.com/flutter/flutter.git -b stable
  • After completion of the download, extract the file in your desired location for example (C:\flutter),
  • Don’t place the Flutter SDK inside the program files it may require some elevated privileges.

Next step is to add the Flutter path in your system environment variable, by the following steps. This enables us to execute all Flutter commands from the command prompt:

  1. From the Windows search look for ‘env’, then select edit environment variables for your account
  2. In under the user variables check there is any variable named Path if exists paste the Flutter SDK full path, example (C:\Flutter\bin) in values if any values exist separate between the two values using ‘;’, if not exists create a new variable name it as path and paste the Flutter SDK location in the value.

Last step in Flutter setup

Open the command prompt, run flutter doctor a command will let you know there are any dependencies to complete the Flutter setup.

If it shows an error like Android license status unknown, you can resolve this by executing the following command line in your terminal.

flutter doctor --android-licenses

If you get logs like the following screenshot you have done.

Setup for Linux

Minimum requirements

  • Minimum disk space around 600MB
  • Operating system Linux 64Bit

Download and setup Flutter

  • Download the Flutter SDK from this link or clone the Flutter’s repository by executing the following command in your terminal,
git clone https://github.com/flutter/flutter.git -b stable --depth 1
  • After completion of the download, extract the file in your desired location for example (/home/`userName`/flutter)
  • Add Flutter tool to your path, open the .bashrc file from your home folder then paste the following line
  • By default the file was been hidden, so check the show hidden files from menu, then open and the add this line
export PATH="$PATH:`pwd`/flutter/bin"

Last step in Flutter setup

Open the terminal, run flutter doctor a command will let you know there are any dependencies to complete the Flutter setup.

If it shows an error like Android license status unknown, you can resolve this by executing the following command line in your terminal

flutter doctor --android-licenses

If you get logs like the following screenshot you have done.

Setup for Mac OS

Minimum requirements

  • Minimum disk space around 2.8Gb and
  • Operating system Linux 64Bit

Download and setup Flutter

  • Download the Flutter SDK from this link or clone the Flutter’s repository from this link,
git clone https://github.com/flutter/flutter.git -b stable --depth 1
  • After completion of the download, unzip the file in the desired location for example (/home/`userName`/flutter)
  • To add the Flutter tool to your path, before that by typing echo $SHELL it will show what shell you are using
  • If you are using the Z shell (ZSH) edit ./zshrc file which is located in your home folder. command + shift + h a shortcut to navigate Home folder in Finder
  • If you’re using Bash shell, edit $HOME/.bashrc or $HOME/.bash_profile. Next is add the following line in the corresponding file by using editor

Last step in Flutter setup

Open the terminal, run flutter doctor a command will let you know there are any dependencies to complete the Flutter setup.

If it shows an error like Android license status unknown, you can resolve this by executing the following command line in your terminal

flutter doctor --android-licenses

If you get logs like the following screenshot you have done.