Implementing Push Notifications in Flutter Using Firebase


How to implement Push Notification in Flutter


Please, support my blog by clicking on our sponsors ad!


Unlocking the Power of Push Notifications in Flutter with Firebase Cloud

Push notifications are an essential aspect of modern mobile applications, allowing developers to engage users even when they are not actively using the app. In Flutter, integrating push notifications can be efficiently done through Firebase Cloud Messaging (FCM). In this tutorial, we'll walk through the steps to set up push notifications in a Flutter app using Firebase and also open specific page when user tap on notification.


Follow steps to create push notification in both project.


Push Notifications in Flutter using Firebase Cloud
Create Project for push notification

After Creating Project add app for both IOS and Android Project.

Push Notification Service
Create app in project

For Both IOS and Android project add Package name. Package name should be same as your package name in Android and Project.

Click on Register App

Flutter app using Firebase Cloud
Download Google Service json.

If you are in android app then download google-services.json else if you are in ios app then download "GoogleService-Info.plist" file

Click Next then click Next then Click Continue to console button.

Step 1: Set up Firebase Project

Firstly, ensure you have a Firebase project created. If not, you can create one from the Firebase Console. Once your project is set up, follow these steps:

Add google-services.json: Download the google-services.json file from Firebase Console and add it to the android/app directory of your Flutter project.

Modify build.gradle Files:

  • In the project-level build.gradle file (android/build.gradle), add the Google services classpath dependency.
dependencies {
    classpath 'com.google.gms:google-services:4.4.1'
}

  • Ensure google() is added in the repositories block in the same file.
  • In the app-level build.gradle file (android/app/build.gradle), add the Google Services plugin and Firebase BOM dependency.
plugins {
    id "com.google.gms.google-services"
}

dependencies {
    implementation platform("com.google.firebase:firebase-bom:32.8.0")
}

Step 2: Install Dependencies
In your Flutter project, open the terminal and execute the following commands one by one:
flutter pub add firebase_core
flutter pub add firebase_messaging
flutter run

Step 3: Implement Push Notification Logic

Now, let's implement the push notification logic. Create a new file named firebase_api.dart inside the lib/api directory. Add the following code to initialize Firebase Messaging:
import 'package:firebase_messaging/firebase_messaging.dart';

class FirebaseApi {
  final _firebaseMessaging = FirebaseMessaging.instance;

  Future<void> initNotifications() async {
    await _firebaseMessaging.requestPermission();
    final fCMToken = await _firebaseMessaging.getToken();
    print('Token:  $fCMToken');
  }
}

Step 4: Integrate Firebase in the Main File

Update your main.dart file to initialize Firebase and request permission for notifications:
import 'dart:io';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:pushnotification/api/firebase_api.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  Platform.isAndroid
      ? await Firebase.initializeApp(
          options: const FirebaseOptions(
              apiKey: 'YOUR_API_KEY',
              appId: 'YOUR_APP_ID',
              messagingSenderId: 'YOUR_SENDER_ID',
              projectId: 'YOUR_PROJECT_ID'))
      : await Firebase.initializeApp();

  await FirebaseApi().initNotifications();
  runApp(const MyApp());
}

Make sure to replace 'YOUR_API_KEY', 'YOUR_APP_ID', 'YOUR_SENDER_ID', and 'YOUR_PROJECT_ID' with your Firebase project credentials from google-services.json.

Step 5: Testing Push Notifications
To test push notifications, ensure your app is running in the background or is closed. You should receive a notification on your device.

When you run the app you will get token "Run" window. copy that token use in firebase console to send notification. 

Now we will test from firebase console.

Go to firebase console -> go to cloud messaging -> Click on New Campaign or Click on Sent first message.

In Notification Section

Firebase Cloud Messaging using Flutter
Setup Notification

Enter Title for Notification Title

Enter Text for Notification

Click on Send test message button

Integrate Firebase with Flutter


Paste Token in textbox and click on round + button
then click on test button.

Go to Target Section

Select the app you want to send and click next button

How to implement Push Notification in Flutter
Target your app

Go to Scheduling Section: select from the option and then click next button and then click on review button

How to implement Push Notification in Flutter
Schedule push notification

Add Additional options (optional)


How to implement Push Notification in Flutter
Schedule Notification

Review message dialog will open Click on Publish button.

How to implement Push Notification in Flutter
Publish notification

Congratulations! You have successfully implemented push notifications in your Flutter app using Firebase. This feature can significantly enhance user engagement and interaction within your application.

In conclusion, implementing push notifications in a Flutter application using Firebase Cloud Messaging (FCM) can greatly enhance user engagement and interaction. Through this tutorial, we've covered the all steps required to integrate push notifications seamlessly into your Flutter project:

Comments

Popular posts from this blog

Explore the UI libraries available for .NET MAUI at no cost.

Push Notification using Firebase in xamarin form (Android and IOS)

School UI Design using xamarin form