Flutter Firebase Cloud Messaging管理插件fcm_channels_manager的使用

发布于 1周前 作者 nodeper 来自 Flutter

Flutter Firebase Cloud Messaging管理插件fcm_channels_manager的使用

插件介绍

fcm_channels_manager 是一个用于在 Android 上创建和管理通知通道的 Flutter 包。它支持 Android 8.0 (API level 26) 及以上版本。

  • 功能
    • 创建新的通知通道。
    • 获取已注册的所有通知通道。
    • 删除已注册的通知通道。

安装

在您的 Flutter 项目 pubspec.yaml 文件中添加以下依赖项:

dependencies:
  fcm_channels_manager: <最新版本>

在您的库文件中添加以下导入:

import 'package:fcm_channels_manager/fcm_channels_manager.dart';

使用示例

1. 创建新通道

成功注册通道后返回成功消息。

final result = await FcmChannelsManager().registerChannel(
  id: "1001",
  name: "Feedback notification",
  description: "Receive new feedback and system's notification",
  importance: NotificationImportance.importanceHight,
  visibility: NotificationVisibility.public,
  bubbles: true,
  vibration: true,
  sound: true,
  badge: true,
);
  • 通知重要性级别
Plugin value Android Reference
NotificationImportance.disabled IMPORTANCE_NONE
NotificationImportance.importanceMin IMPORTANCE_MIN
NotificationImportance.importanceLow IMPORTANCE_LOW
NotificationImportance.importanceDefault IMPORTANCE_DEFAULT
NotificationImportance.importanceHight IMPORTANCE_HIGH
  • 通知可见性
Plugin value 描述
NotificationVisibility.public 在所有锁屏上显示此通知
NotificationVisibility.private 在所有锁屏上显示此通知,但在安全锁屏上隐藏敏感或私密信息
NotificationVisibility.secret 不在安全锁屏上显示任何部分此通知
2. 获取所有注册的通道

获取所有注册的通道及其基本信息:idnamedescriptionimportance。可以检查重要性级别并处理业务逻辑。

final channels = await FcmChannelsManager().getChannels();
3. 删除一个通道

删除已注册的通道,并返回删除成功的消息。

final result = await FcmChannelsManager().unregisterChannel('1001');
4. 提供应用程序通知设置

更新 .providesAppNotificationSettings 并返回成功状态。该函数应在请求通知权限后调用(使用 firebase_messaging)。

FcmChannelsManager()
  .providesAppNotificationSettings()
  .then((value) =&gt; log('Permission status: $value'));

示例代码

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:fcm_channels_manager/fcm_channels_manager.dart';

void main() {
  runApp(const MyApp());
}

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

  [@override](/user/override)
  State&lt;MyApp&gt; createState() =&gt; _MyAppState();
}

class _MyAppState extends State&lt;MyApp&gt; with WidgetsBindingObserver {
  final _fcmChannelsManagerPlugin = FcmChannelsManager();
  List&lt;NotificationChannel&gt; _channels = List.from([]);

  [@override](/user/override)
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      initChannels();
    });

    WidgetsBinding.instance.addObserver(this);
  }

  [@override](/user/override)
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  [@override](/user/override)
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      _getChannels();
    }
  }

  Future&lt;void&gt; _getChannels() async {
    _channels = await _fcmChannelsManagerPlugin.getChannels();
    setState(() {});
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future&lt;void&gt; initChannels() async {
    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    final List&lt;Map&lt;String, dynamic&gt;&gt; _mockData = [
      {
        'id': '1001',
        'name': 'Social notification',
        'description': 'Social notification',
        'importance': NotificationImportance.importanceHight,
      },
      {
        'id': '1002',
        'name': 'Message notification',
        'description': 'Message notification',
        'importance': NotificationImportance.importanceDefault,
      },
      {
        'id': '1003',
        'name': 'System notification',
        'description': 'Admin notification',
        'importance': NotificationImportance.importanceLow,
      },
      {
        'id': '1004',
        'name': 'Report notification',
        'description': 'User report notification',
        'importance': NotificationImportance.importanceMin,
      }
    ];
    for (var channel in _mockData) {
      await _fcmChannelsManagerPlugin.registerChannel(
        id: channel['id'],
        name: channel['name'],
        description: channel['description'],
        importance: channel['importance'],
      );
    }
    _getChannels();
  }

  Future&lt;void&gt; unRegisterFirst() async {
    await _fcmChannelsManagerPlugin.unregisterChannel('1001');
    _getChannels();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: [
            ListView.builder(
              itemBuilder: (_, index) {
                final channel = _channels[index];
                return Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            channel.name,
                            style: const TextStyle(
                              fontWeight: FontWeight.w700,
                              fontSize: 16,
                            ),
                          ),
                          Text(channel.importance.toString()),
                        ],
                      ),
                    ),
                    Switch(
                      value:
                          channel.importance != NotificationImportance.disabled,
                      onChanged: (_) {},
                    )
                  ],
                );
              },
              shrinkWrap: true,
              itemCount: _channels.length,
            ),
            const SizedBox(height: 10),
            const Divider(),
            const SizedBox(height: 10),
            ElevatedButton(
              onPressed: () {
                unRegisterFirst();
              },
              child: const Text('Unregister channel 1001'),
            ),
          ],
        ),
      ),
    );
  }
}

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

1 回复

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


在Flutter项目中,使用fcm_channels_manager插件可以方便地管理Firebase Cloud Messaging (FCM)的通知渠道。这对于Android设备尤为重要,因为从Android O(API级别26)开始,所有的通知都必须分配到一个通知渠道。

以下是一个简单的示例,展示了如何在Flutter项目中集成并使用fcm_channels_manager来管理FCM通知渠道。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^1.10.0  # 确保你有Firebase核心插件
  firebase_messaging: ^11.2.0  # FCM插件
  fcm_channels_manager: ^0.4.0  # fcm_channels_manager插件,版本号请根据实际情况调整

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

2. 配置Firebase

确保你的Firebase项目已经配置正确,并且你已经在你的Flutter项目中添加了google-services.json(对于Android)和GoogleService-Info.plist(对于iOS)。

3. 初始化Firebase和FCM

在你的main.dart文件中,初始化Firebase和FCM:

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:fcm_channels_manager/fcm_channels_manager.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  // Initialize FCM
  FirebaseMessaging.instance.onNewMessage.listen((RemoteMessage message) {
    print('A new FCM message arrived!');
    // Handle incoming message
  });

  // Setup FCM Channels Manager
  await setupFCMChannels();

  runApp(MyApp());
}

Future<void> setupFCMChannels() async {
  // Define your notification channels
  var channels = [
    FCMChannel(
      id: 'high_importance_channel',
      title: 'High Importance Notifications',
      description: 'This channel is used for high importance notifications',
      importance: Importance.high,
      sound: true,
    ),
    FCMChannel(
      id: 'default_channel',
      title: 'Default Notifications',
      description: 'This channel is used for default notifications',
      importance: Importance.defaultImportance,
      sound: true,
    ),
  ];

  // Create/Update the channels
  await FCMChannelsManager().createOrUpdateChannels(channels);
}

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

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Text('FCM Channels are set up!'),
      ),
    );
  }
}

4. 处理通知点击事件

你可能还想处理用户点击通知时的事件。你可以在FirebaseMessaging.onMessageOpenedApp流中监听这些事件:

FirebaseMessaging.instance.onMessageOpenedApp.listen((RemoteMessage message) {
  print('A message was opened while the app was in the background!');
  // Navigate to a specific page or handle the message data
  if (message.data.containsKey('type')) {
    // Example: Navigate based on the message type
    Navigator.pushNamed(context, '/${message.data['type']}');
  }
});

注意:上面的代码片段假设你有一个命名路由系统来导航到不同的页面。

5. 测试通知

最后,使用Firebase控制台或其他工具发送测试通知到你的设备,确保通知渠道已正确设置,并且通知能够按预期显示。

这个示例展示了如何使用fcm_channels_manager插件来创建和管理Firebase Cloud Messaging的通知渠道。根据你的应用需求,你可能需要调整通道的配置和处理逻辑。

回到顶部