Flutter Firebase通知插件hg_notification_firebase的使用

Flutter Firebase通知插件hg_notification_firebase的使用

hg_notification_firebase 是一个用于处理 Firebase 通知的 Flutter 插件。它可以帮助开发者轻松实现推送通知的功能,并且支持在应用前台或后台时接收通知。

使用步骤

1. 添加依赖

pubspec.yaml 文件中添加以下依赖:

dependencies:
  firebase_core: ^2.10.0
  hg_notification_firebase: ^1.0.0

然后运行 flutter pub get 来安装依赖。

2. 初始化 Firebase

确保在 main.dart 文件中正确初始化 Firebase:

import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:hg_notification_firebase/hg_notification_firebase.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized(); // 确保 Flutter 绑定完成
  await Firebase.initializeApp(); // 初始化 Firebase
  runApp(const MyApp());
}

3. 配置通知插件

使用 HGNotificationFirebase 包裹你的 MaterialAppCupertinoApp,并设置相关的回调函数来处理通知事件。

完整示例代码

import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:hg_notification_firebase/hg_notification_firebase.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized(); // 确保 Flutter 绑定完成
  await Firebase.initializeApp(); // 初始化 Firebase
  runApp(const MyApp());
}

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

  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return HGNotificationFirebase( // 使用通知插件包裹 MaterialApp
      defaultNavigatorKey: GlobalKey<NavigatorState>(), // 提供默认的 NavigatorKey
      onOpenNotificationArrive: (_, payload) { // 处理应用前台收到的通知
        log(
          id,
          msg: "Notification received while app is open with payload $payload",
        );
      },
      onTap: (navigatorState, appState, payload) { // 处理通知点击事件
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('appState: $appState\npayload: $payload')),
        );
        log(
          id,
          msg: "Notification tapped with $appState & payload $payload",
        );
      },
      onFCMTokenInitialize: (_, token) { // 处理 FCM Token 初始化
        log(id, msg: "FCM Token initialized: $token");
      },
      onFCMTokenUpdate: (_, token) { // 处理 FCM Token 更新
        log(id, msg: "FCM Token updated: $token");
      },
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Firebase Notifications Demo',
        home: const MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Firebase Notifications Demo'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pushNamed(context, '/second');
          },
          child: const Text('Go to Second Page'),
        ),
      ),
    );
  }
}

更多关于Flutter Firebase通知插件hg_notification_firebase的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter Firebase通知插件hg_notification_firebase的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


hg_notification_firebase 是一个用于在 Flutter 应用中集成 Firebase 通知的插件。它简化了 Firebase Cloud Messaging (FCM) 的集成过程,使得开发者可以轻松地在应用中接收和处理推送通知。

以下是如何在 Flutter 项目中使用 hg_notification_firebase 插件的步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 hg_notification_firebase 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  hg_notification_firebase: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 配置 Firebase

在 Firebase 控制台中创建一个新的项目,并按照以下步骤配置 Firebase:

  1. 添加 Android 应用

    • 在 Firebase 控制台中,点击“添加应用”并选择 Android。
    • 输入应用的包名(例如 com.example.myapp)。
    • 下载 google-services.json 文件,并将其放置在 android/app 目录下。
  2. 添加 iOS 应用

    • 在 Firebase 控制台中,点击“添加应用”并选择 iOS。
    • 输入应用的 Bundle ID。
    • 下载 GoogleService-Info.plist 文件,并将其放置在 ios/Runner 目录下。
  3. 配置 Firebase SDK

    • android/build.gradle 文件中添加以下内容:

      dependencies {
          classpath 'com.google.gms:google-services:4.3.10'  // 使用最新版本
      }
      
    • android/app/build.gradle 文件中添加以下内容:

      apply plugin: 'com.android.application'
      apply plugin: 'com.google.gms.google-services'
      
    • ios/Podfile 文件中添加以下内容:

      platform :ios, '10.0'
      use_frameworks!
      
      target 'Runner' do
        pod 'Firebase/Core'
        pod 'Firebase/Messaging'
      end
      

3. 初始化 Firebase

main.dart 文件中初始化 Firebase:

import 'package:flutter/material.dart';
import 'package:hg_notification_firebase/hg_notification_firebase.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await HgNotificationFirebase.initialize();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

4. 处理通知

main.dart 文件中设置通知处理逻辑:

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _notificationTitle = 'No Notification';
  String _notificationBody = 'No Notification';

  @override
  void initState() {
    super.initState();
    HgNotificationFirebase.onMessage.listen((RemoteMessage message) {
      setState(() {
        _notificationTitle = message.notification?.title ?? 'No Title';
        _notificationBody = message.notification?.body ?? 'No Body';
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Firebase Notification Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Notification Title:',
              style: TextStyle(fontSize: 20),
            ),
            Text(
              _notificationTitle,
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 20),
            Text(
              'Notification Body:',
              style: TextStyle(fontSize: 20),
            ),
            Text(
              _notificationBody,
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
          ],
        ),
      ),
    );
  }
}

5. 发送测试通知

在 Firebase 控制台中,进入 Cloud Messaging 部分,点击 New Notification 来发送测试通知。确保在通知中填写标题和内容,并选择目标设备。

6. 运行应用

运行你的 Flutter 应用,并确保在设备上接收到通知。当应用在前台时,通知内容将显示在应用界面上。

7. 处理后台通知

如果需要在应用处于后台或关闭时处理通知,可以使用 HgNotificationFirebase.onBackgroundMessage 方法:

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  print("Handling a background message: ${message.messageId}");
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await HgNotificationFirebase.initialize();
  HgNotificationFirebase.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(MyApp());
}

8. 获取设备令牌

如果需要获取设备的 FCM 令牌,可以使用以下代码:

String? token = await HgNotificationFirebase.getToken();
print("FCM Token: $token");

9. 处理点击通知

当用户点击通知时,可以通过 HgNotificationFirebase.onMessageOpenedApp 来处理:

HgNotificationFirebase.onMessageOpenedApp.listen((RemoteMessage message) {
  print("Notification clicked: ${message.notification?.title}");
});
回到顶部