패키지, 저장소 및 앱 카테고리 검색

firebase_notifications_handler 표지
패키지 상세v3.0.3

firebase_notifications_handler

간편한 사용을 위한 Firebase 알림 핸들러로 내장된 로컬 알림 지원 기능을 통해 추가 설정 없이 앱이 프론트엔드에서 알림을 표시할 수 있습니다.

AndroidiOSmacOS
30일 다운로드
322
좋아요
50
Pub 점수
160

패키지 설치

flutter pub add firebase_notifications_handler

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Firebase Cloud Messaging (FCM) 알림을 단순화하고 내장된 로컬 알림 지원 기능을 제공하는 간단한 Flutter 패키지입니다. 추가 구성 없이 포그라운드에서 알림을 표시할 수 있어 사용자 참여도를 향상시킵니다. 핸들러는 안드로이드, iOS, macOS에서 원격 및 로컬 알림을 원활하게 관리합니다. 최소한의 반복 코드로 푸시 알림을 처리하려는 개발자에게 이상적입니다.

사용 사례

  • 포그라운드에서 FCM 알림 처리
  • 로컬 알림과 원격 알림을 함께 표시
  • Flutter 앱에서 푸시 알림 설정을 간소화하기
  • 앱 재시작 없이 실시간 알림 활성화
  • 다중 플랫폼 알림 전달 지원

주요 기능

  • 내장된 로컬 알림 지원
  • 포그라운드 알림을 위한 최소 설정
  • 다중 플랫폼 호환성 (Android, iOS, macOS)
  • FCM 메시지 라이프사이클의 자동 처리
  • 정제된, 쉽게 통합할 수 있는 API

적합한 대상

  • Firebase Cloud Messaging를 사용하는 Flutter 앱
  • 빠른 알림 통합을 원하는 개발자
  • 원격 및 로컬 알림을 모두 필요로 하는 앱
  • 다중 플랫폼 대상 프로젝트
  • 개발 속도를 우선시하는 팀

고려 사항

  • 각 플랫폼에서 Firebase 설정이 필요합니다
  • 완전한 네이티브 솔루션과 비교해 맞춤 설정이 제한적
  • 기반 Firebase SDK에 따라 다름
  • 백그라운드 실행을 위해 추가 권한이 필요할 수 있습니다
  • 복잡한 알림 워크플로에 적합하지 않습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

FirebaseNotificationsHandler For Flutter

pub package downloads likes pub points license MIT

portfolio publisher


FirebaseNotificationsHandler is a simple and easy-to-use notifications handler for Firebase Notifications. It includes built-in support for local notifications, allowing your app to display notifications even when it's in the foreground with no extra setup. With customization options available, you can manage notification behavior seamlessly.

The package uses a widget-based approach, and exposes a widget to handle the notifications. This makes it feel like home for Flutter developers, as it integrates seamlessly with Flutter’s UI-driven architecture. With easy-to-use callbacks such as onTap, you can effortlessly manage and respond to notification taps and customize the notification behavior, providing a smooth integration process for any Flutter project.


🗂️ Table of Contents


📷 Screenshots

App In Foreground App In Background Expanded Notification

✨ Features

  • Foreground Notification Handling: The package allows you to manage notifications even when the app is in the foreground, without needing additional setup.
  • Easy-to-use Callbacks: You can define custom callbacks when a notification is tapped (onTap), when a notification arrives when app open (onOpenNotificationArrive), etc., making the widget simple to use.
  • Custom Sounds: The package supports custom notification sounds for both Android and iOS platforms.
  • Automatic FCM Token Handling: Built-in functionality to automatically handle Firebase Cloud Messaging (FCM) token initialization and updates, ensuring seamless management of push notification tokens.
  • Cross-Platform Support: It provides full support for both Android and iOS, ensuring a consistent experience across platforms.
  • Widget-Based Approach: The package integrates well with Flutter’s UI-driven architecture, offering a widget-based solution for handling notifications.
  • Stream Subscription for Notifications: Exposes various streams like notificationTapsSubscription, notificationArrivesSubscription allowing listening to important notification events and managing them easily with the provided NotificationInfo objects.
  • Deep Customization: The package offers flexibility in customizing notification behavior, such as controlling which notifications are handled, defining custom actions for specific notifications, and setting platform-specific parameters for local notifications.
  • Solutions for Common Issues: The README provides troubleshooting tips and solutions for commonly faced issues, such as notifications not appearing as pop-ups, custom sounds not working in release mode, and image handling limitations.

🛫 Migration Guides

Migration Guide from v2.x to v3.x+

1. Minimum SDK versions raised
  • Requires Dart 3.10 / Flutter 3.38.1 or newer, up from Dart 3.3 / Flutter 3.19.
  • Android minSdk must be at least 24.
2. Android now requires core library desugaring

flutter_local_notifications 22 requires the consuming app to enable desugaring and compile against Java 17. Without it the build fails with Dependency ':flutter_local_notifications' requires core library desugaring to be enabled. See Platform-Specific Setup → Android for the exact configuration.

3. sendLocalNotification no longer takes uiLocalNotificationDateInterpretation

UILocalNotificationDateInterpretation was removed upstream in flutter_local_notifications v22, so the parameter is gone. Remove the argument from your calls — there is no replacement:

await FirebaseNotificationsHandler.sendLocalNotification(
  id,
  notificationDetails: details,
  scheduledDateTime: when,
  androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
  // uiLocalNotificationDateInterpretation: ...,  <-- delete this line
);
4. Re-exported plugins had major upgrades

This package re-exports firebase_messaging and flutter_local_notifications, so their breaking changes reach your code directly. firebase_messaging moved 15 → 16 and flutter_local_notifications 18 → 22; most notably the latter moved show, zonedSchedule and initialize to named parameters.

5. Localized notifications

Messages sent with title_loc_key / body_loc_key carry no title or body, so they previously rendered blank. Provide titleGetter / bodyGetter in LocalNotificationsConfiguration to resolve them against your app's own localizations.

For more details, refer to the CHANGELOG.


Migration Guide from v1.x to v2.x+

1. Renaming of Parameters and Callbacks

Several parameters and callbacks were renamed for clarity and consistency:

  • NotificationTapDetails is now NotificationInfo.
  • onFCMTokenInitialize is now onFcmTokenInitialize.
  • onFCMTokenUpdate is now onFcmTokenUpdate.
  • initializeFCMToken is now initializeFcmToken.
  • requestPermissionsOnInit is now requestPermissionsOnInitialize.
  • AppState.closed is now AppState.terminated.
2. Context and Navigator Key Removal
  • Navigator Key: The navigatorKey parameter is no longer available in onTap and onOpenNotificationArrive. You’ll need to manage your own navigator key in your app. See the example app for more details on handling navigation.
  • Context: Callbacks such as onFcmTokenInitialize and onFcmTokenUpdate no longer accept context. Ensure that any context-dependent logic is refactored.
3. Handling of Notifications
  • NotificationInfo: The class NotificationTapDetails has been renamed to NotificationInfo. This class now includes the firebaseMessage parameter, providing more comprehensive information.
  • onTap and onOpenNotificationArrive now return a NotificationInfo object, replacing the previous payload. The payload can still be accessed using the payload property of NotificationInfo.
  • The notificationArrivesSubscription stream now returns NotificationInfo instead of just the payload.
4. Local Notifications Configuration

The configuration of local notifications has been refactored to use platform-specific getters in LocalNotificationsConfiguration:

  • Android-specific parameters like channelId, channelName, and sound have been moved to localNotificationsConfiguration.androidConfig.
  • iOS-specific parameters like sound have been moved to localNotificationsConfiguration.iosConfig.
  • The notificationIdGetter function is now also part of the LocalNotificationsConfiguration.
5. FCM Token Changes
  • The callback onFCMTokenRefresh has been removed. Use onFcmTokenUpdate instead to handle token updates.
  • If you need to maintain your own stream of FCM tokens, you can do so manually in your app.
6. Notification Sending
  • Removed: sendFcmNotification has been deprecated for sending notifications from the client side. You'll now need to send notifications using Firebase Cloud Messaging (FCM) server-side APIs.
  • New: A new sendLocalNotification function is introduced, which allows sending or scheduling local notifications.
7. Other Notable Changes
  • New streams notificationTapsSubscription and notificationArrivesSubscription are available for handling notification taps and arrivals.
  • Android notification channel management methods have been added: create, read, and delete channels.
  • New callbacks and getters such as permissionGetter, shouldHandleNotification, messageModifier, and stateKeyGetter are introduced for finer control over the notification lifecycle.
  • Logging is now available in debug mode for better debugging.
  • Fixed issues with images not displaying in notifications.
  • getInitialMessage callback added for retrieving the initial notification that launched the app.
8. Updated Example App and Documentation
  • The example app has been updated to use the latest SDKs and demonstrates how to implement these breaking changes.
  • Documentation has been updated to reflect all changes, along with the issue tracker link for reporting bugs or issues.

For more details, refer to the CHANGELOG.


🚀 Getting Started

Step 1: Create Firebase Project

Create a Firebase project. Learn more about Firebase projects here.

Step 2: Register your apps and configure Firebase

Add your Android & iOS apps to your Firebase project and configure the Firebase the apps by following the setup instructions for Android and iOS separately.

Step 3: Add firebase_core dependency

Add firebase_core as a dependency in your pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter

  firebase_core:

Step 4: Initialize Firebase

Call Firebase.initializeApp() in the main() method as shown to intialize Firebase in your project.

import 'package:firebase_core/firebase_core.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  runApp(MyApp());
}

🛠️ Platform-Specific Setup

Android

[!IMPORTANT] flutter_local_notifications requires core library desugaring. Without it the build fails with Dependency ':flutter_local_notifications' requires core library desugaring to be enabled. This applies even if you never schedule notifications. Android minSdk must also be at least 24.

  1. Enable desugaring in android/app/build.gradle:
android {
    compileOptions {
        coreLibraryDesugaringEnabled = true
        sourceCompatibility = JavaVersion.VERSION_17
        targetCompatibility = JavaVersion.VERSION_17
    }

    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_17
    }
}

dependencies {
    coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
}

[!NOTE] For the current desugar_jdk_libs version and the rest of the platform specific setup for local notifications, refer here

  1. Add the following meta-data tags (if required) to define default values in AndroidManifest.xml under the <application> tag:
<!-- Can add a default notification channel (if not sending a channel id when sending notification) -->
<!-- If you don't specify a default channel id, and don't pass an id when sending notification, Android creates a default channel "Miscellaneous" -->
<meta-data
    android:name="com.google.firebase.messaging.default_notification_channel_id"
    android:value="default" />

<!-- Use the following tags if you need to different icons or color for app icon -->
<!-- <meta-data
    android:name="com.google.firebase.messaging.default_notification_icon"
    android:resource="@drawable/notification_icon" />

<meta-data
    android:name="com.google.firebase.messaging.default_notification_color"
    android:resource="@color/notification_color" /> -->
  1. Add this <intent-filter> in the <activity> tag:
<intent-filter>
    <action android:name="FLUTTER_NOTIFICATION_CLICK" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

iOS

[!NOTE] Refer to the platform specific setup for local notifications here

Web

  1. Provide the vapidKey in FirebaseNotificationsHandler from the cloud messaging settings by generating a new Web push certificate.

  2. Add this script tag in index.html after adding the firebase config script

<script>
if ("serviceWorker" in navigator) {
  window.addEventListener("load", function () {
    // navigator.serviceWorker.register("/flutter_service_worker.js");
    navigator.serviceWorker.register("/firebase-messaging-sw.js");
  });
}
</script>
  1. Create a file firebase-messaging-sw.js in the web folder itself and paste the following contents. Add your own firebase app config here.
importScripts("https://www.gstatic.com/firebasejs/7.15.5/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/7.15.5/firebase-messaging.js");

firebase.initializeApp(
    // YOUR FIREBASE CONFIG MAP HERE
);

const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
    const promiseChain = clients
        .matchAll({
            type: "window",
            includeUncontrolled: true
        })
        .then(windowClients => {
            for (let i = 0; i < windowClients.length; i++) {
                const windowClient = windowClients[i];
                windowClient.postMessage(payload);
            }
        })
        .then(() => {
            return registration.showNotification("New Message");
        });
    return promiseChain;
});
self.addEventListener('notificationclick', function (event) {
    console.log('notification received: ', event)
});

❓ Usage

  1. Add firebase_notifications_handler as a dependency in your pubspec.yaml file.
dependencies:
  flutter:
    sdk: flutter

  firebase_notifications_handler:
  1. Wrap the FirebaseNotificationsHandler widget ideally as a parent widget on the MaterialApp to enable your application to receive notifications.
import 'package:firebase_notifications_handler/firebase_notifications_handler.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FirebaseNotificationsHandler(
      child: MaterialApp(),
    );
  }
}

Although, the widget automatically initializes the FCM token, but if the FCM token is needed before the widget is built, use the FirebaseNotificationsHandler.initializeFcmToken() function to initialize the token, which will initialize and return initialized token. This will also trigger the onFCMTokenInitialize callback.

  1. Explore the widget documentation, and see the different configurations available, allowing you to customize each and every bit of your notifications.
FirebaseNotificationsHandler(
  localNotificationsConfiguration: LocalNotificationsConfiguration(
    androidConfig: AndroidNotificationsConfig(
      // ...
    ),
    iosConfig: IosNotificationsConfig(
      // ...
    ),
  ),
  onOpenNotificationArrive: (info) {
    log(
      id,
      msg: 'Notification received while app is open with payload ${info.payload}',
    );
  },
  onTap: (info) {
    final payload = info.payload;
    final appState = info.appState;
    final firebaseMessage = info.firebaseMessage;

    // If you want to push a screen on notification tap
    //
    // Globals.navigatorKey.currentState?.pushNamed(payload['screenId']);
    //
    // OR
    ///
    // Get current context
    // final context = Globals.navigatorKey.currentContext!;

    log(
      id,
      msg: 'Notification tapped with $appState & payload $payload. Firebase message: $firebaseMessage',
    );
  },
  onFcmTokenInitialize: (token) => Globals.fcmTokenNotifier.value = token,
  onFcmTokenUpdate: (token) => Globals.fcmTokenNotifier.value = token,
  // ...
);

Creating notification channels for Android

By default, if you send a notification, the device will automatically create a notification channel with the passed channelId, but the priority for that channel will be normal, and the notification will not show up as a popup.

Creating a default channel lets you set the priorty to high and also give you more customization of the channels like setting a custom notification sound, setting vibration patterns etc.

FirebaseNotificationsHandler.createAndroidNotificationChannel(
  const AndroidNotificationChannel(
    'marketing',
    'Marketing',
    description: 'Notification channel for marketing',
    playSound: true,
    importance: Importance.max,
    sound: RawResourceAndroidNotificationSound('marketing'),
  ),
);

It is recommended to create notification channels as soon as the app starts, as the custom sounds will not play if the channel is not created for the first time, and it might cause issues with other parameters as well.

FirebaseNotificationsHandler.createAndroidNotificationChannels([
  const AndroidNotificationChannel(
    'promotions',
    'Promotions',
    description: 'Notification channel for promotions',
    playSound: true,
    importance: Importance.max,
    sound: RawResourceAndroidNotificationSound('chime'),
  ),
  const AndroidNotificationChannel(
    'order-updates',
    'Order Updates',
    description: 'Notification channel for order updates',
    playSound: true,
    importance: Importance.max,
    sound: RawResourceAndroidNotificationSound('elevator'),
  ),
  const AndroidNotificationChannel(
    'messages',
    'Messages',
    description: 'Notification channel for messages',
    playSound: true,
    importance: Importance.max,
    sound: RawResourceAndroidNotificationSound('bell'),
  ),
]);

Adding custom sound files in platform-specific folders

Android

[!IMPORTANT] Add a keep.xml file in the android/app/src/main/res/raw/ folder, as flutter strips off the raw folder when compiling app in release mode, and hence the custom sounds won't work in release mode.

  • Add the audio file in the android/app/src/main/res/raw/ folder.
iOS
  • Add the audio file in the ios/Runner/Resources/ folder.

💡 Solutions to common issues

Notification not showing as a pop up on Android device:

On Android devices, a notification channel by default when a notification arrives, but that might not have the priority set to high. The notification only shows up as a popup if the channel you're sending it to has priority set as "high". We can solve this issue by creating a notification channel on app start using:

FirebaseNotificationsHandler.createAndroidNotificationChannel(
  const AndroidNotificationChannel(
    'default',
    'Default',
    importance: Importance.high,
  ),
);

Custom sound not playing when notification received on Android device:

On Android devices, a notification channel by default when a notification arrives, but that won't have the sound set to it by default. The sound will only play if the channel was creating while specifying the custom sound you want to play for that channel.

[!NOTE] You cannot modify a channel's sound after it's created. Only way is to either use a new channel id or delete an existing channel using FirebaseNotificationsHandler.deleteAndroidNotificationChannel(String channelId); and creating a new one with the new sound. Or try uninstalling the app and creating the channel again.

We can solve this issue by creating a notification channel on app start and passing in the sound using:

FirebaseNotificationsHandler.createAndroidNotificationChannel(
  const AndroidNotificationChannel(
    'default',
    'Default',
    playSound: true,
    importance: Importance.high,
    sound: RawResourceAndroidNotificationSound('pop'),
  ),
);

Notification image not showing if app in background or terminated even when passed on Android device:

The max size for a notification to be displayed by firebase on an Android device is 1MB (Source). So, if an image exceeds this size, it is not shown in the notification. However, if the app is in foreground, then there is no size limitation as then it's handled by local notifications.

Custom sounds in Android work in debug mode but not in release mode:

Flutter strips off the raw folder during compiling build for release mode. We can add a file keep.xml in the raw folder, which tells flutter to not strip off the raw folder, and hence fixing the issue.


🎯 Sample Usage

See the example app for a complete app. Learn how to setup the example app for testing here.

Check out the full API reference of the widget here.

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_notifications_handler/firebase_notifications_handler.dart';
import 'package:flutter/material.dart';
import 'package:notifications_handler_demo/firebase_options.dart';
import 'package:notifications_handler_demo/screens/splash_screen.dart';
import 'package:notifications_handler_demo/utils/app_theme.dart';
import 'package:notifications_handler_demo/utils/globals.dart';
import 'package:notifications_handler_demo/utils/helpers.dart';
import 'package:notifications_handler_demo/utils/route_generator.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  runApp(const _MainApp());
}

class _MainApp extends StatelessWidget {
  static const id = '_MainApp';

  const _MainApp();

  @override
  Widget build(BuildContext context) {
    return FirebaseNotificationsHandler(
      localNotificationsConfiguration: LocalNotificationsConfiguration(
        androidConfig: AndroidNotificationsConfig(
            // ...
        ),
        iosConfig: IosNotificationsConfig(
            // ...
        ),
      ),
      shouldHandleNotification: (msg) {
        // add some logic and return bool on whether to handle a notif or not
        return true;
      },
      onOpenNotificationArrive: (info) {
        log(
          id,
          msg: 'Notification received while app is open with payload ${info.payload}',
        );
      },
      onTap: (info) {
        final payload = info.payload;
        final appState = info.appState;
        final firebaseMessage = info.firebaseMessage;

        /// If you want to push a screen on notification tap
        ///
        // Globals.navigatorKey.currentState?.pushNamed(
        //   payload['screenId'],
        // );
        ///
        /// or
        ///
        /// Get current context
        // final context = Globals.navigatorKey.currentContext!;

        log(
          id,
          msg: 'Notification tapped with $appState & payload $payload. Firebase message: $firebaseMessage',
        );
      },
      onFcmTokenInitialize: (token) => Globals.fcmTokenNotifier.value = token,
      onFcmTokenUpdate: (token) => Globals.fcmTokenNotifier.value = token,
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'FirebaseNotificationsHandler Demo',
        navigatorKey: Globals.navigatorKey,
        scaffoldMessengerKey: Globals.scaffoldMessengerKey,
        theme: AppTheme.lightTheme,
        darkTheme: AppTheme.darkTheme,
        onGenerateRoute: RouteGenerator.generateRoute,
        initialRoute: SplashScreen.id,
      ),
    );
  }
}

👤 Author

Built and maintained by Rithik Bhandari, a mobile developer building cross-platform apps with Flutter.

카테고리

의존성

의존성 목록 6 개

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.