Flutter通知渠道管理插件flutter_notification_channel的使用

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

Flutter通知渠道管理插件flutter_notification_channel的使用

flutter_notification_channel 是一个用于在 Android 上注册带有自定义配置的通知渠道的插件。对于更多细节,可以阅读 Android 官方文档

为什么需要它?

例如,firebase_messaging 版本 7.0.3 及以下不支持设置通知渠道,因此通知可能不会播放声音或在锁屏上显示,也不会出现气泡等。这个插件的主要目的是在 Android 上创建带有自定义配置的通知渠道,并与 firebase_messaging 一起使用。

如何使用

只需像下面这样调用即可:

var result = await FlutterNotificationChannel().registerNotificationChannel(
    description: 'Your channel description',
    id: 'your_channel_id',
    importance: NotificationImportance.IMPORTANCE_HIGH,
    name: 'Your channel name',
    visibility: NotificationVisibility.VISIBILITY_PUBLIC,
    allowBubbles: true,
    enableVibration: true,
    enableSound: true,
    showBadge: true,
);
print(result);

然后,当你通过 Firebase 发送消息时,请指定 android_channel_idsound 参数为 "default",以便在你设置了插件中的 enableSound 后播放默认声音。如果不这样做,在 Android 9 及以上版本中将不会播放任何声音。

{
  "notification": {
    "title": "Your message title",
    "body": "Your message body",
    "android_channel_id": "your_channel_id",
    "sound": "default"
  },
  "data": {
    "click_action" : "FLUTTER_NOTIFICATION_CLICK",
  },
  "priority": "high",
  "content_available": true,
  "to": "YOUR_FIREBASE_PUSH_TOKEN_GOES_HERE"
}

示例代码

以下是一个完整的示例代码,展示了如何注册一个通知渠道:

import 'package:flutter/material.dart';
import 'package:flutter_notification_channel/flutter_notification_channel.dart';
import 'package:flutter_notification_channel/notification_importance.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Register Channel'),
        ),
        body: Center(
          child: Column(
            children: [
              MaterialButton(
                onPressed: () async {
                  debugPrint('start registering');
                  var result = await FlutterNotificationChannel()
                      .registerNotificationChannel(
                    description: 'My test channel',
                    id: 'com.softmaestri.testchannel',
                    importance: NotificationImportance.IMPORTANCE_HIGH,
                    name: 'Flutter channel test name',
                  );
                  debugPrint('Result: $result');
                },
                child: const Text('Register channel'),
              )
            ],
          ),
        ),
      ),
    );
  }
}

在这个示例中,点击按钮后会注册一个新的通知渠道,并打印注册结果。你可以根据需要修改渠道的参数来适应你的应用需求。


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

1 回复

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


当然,以下是如何在Flutter项目中使用flutter_notification_channel插件来管理Android通知渠道的示例代码。

首先,确保你已经在pubspec.yaml文件中添加了flutter_notification_channel依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_local_notifications: ^9.0.0  # 这个插件通常会和flutter_notification_channel一起使用
  flutter_notification_channel: ^1.0.0  # 添加此依赖

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

接下来,在你的Flutter项目中,按照以下步骤配置和使用通知渠道:

  1. 导入必要的包
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_notification_channel/flutter_notification_channel.dart';
  1. 初始化Flutter Local Notifications和Notification Channels
void main() {
  WidgetsFlutterBinding.ensureInitialized();
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  // Android initialization
  const AndroidInitializationSettings androidInitializationSettings = AndroidInitializationSettings('@mipmap/ic_launcher');

  // iOS initialization (optional, only if you support iOS)
  const IOSInitializationSettings iosInitializationSettings = IOSInitializationSettings(
    requestAlertPermission: true,
    requestBadgePermission: true,
    requestSoundPermission: true,
  );

  // Platform specific initialization settings
  const InitializationSettings initializationSettings = InitializationSettings(
    android: androidInitializationSettings,
    iOS: iosInitializationSettings,
  );

  flutterLocalNotificationsPlugin.initialize(initializationSettings,
      onSelectNotification: (String? payload) async {
    if (payload != null) {
      showDialog(
        context: navigatorKey.currentContext!,
        builder: (BuildContext context) => CupertinoAlertDialog(
          title: Text('Payload'),
          content: Text(payload),
        ),
      );
    }
  });

  // Create notification channels (Android specific)
  _createNotificationChannels(flutterLocalNotificationsPlugin);

  runApp(MyApp());
}

Future<void> _createNotificationChannels(FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin) async {
  // Define a channel (Android specific)
  const String highImportanceChannel = 'high_importance_channel';
  const String defaultImportanceChannel = 'default_importance_channel';
  const String lowImportanceChannel = 'low_importance_channel';

  // Create a new channel for high importance notifications
  const AndroidNotificationChannel highImportanceChannelDetails = AndroidNotificationChannel(
    highImportanceChannel,
    'High Importance Notifications',
    'This channel is used for high importance notifications',
    importance: Importance.high,
    playSound: true,
  );

  // Create a new channel for default importance notifications
  const AndroidNotificationChannel defaultImportanceChannelDetails = AndroidNotificationChannel(
    defaultImportanceChannel,
    'Default Importance Notifications',
    'This channel is used for default importance notifications',
    importance: Importance.defaultImportance,
    playSound: true,
  );

  // Create a new channel for low importance notifications
  const AndroidNotificationChannel lowImportanceChannelDetails = AndroidNotificationChannel(
    lowImportanceChannel,
    'Low Importance Notifications',
    'This channel is used for low importance notifications',
    importance: Importance.low,
    playSound: false,
  );

  // Create the channels
  await flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannels([highImportanceChannelDetails, defaultImportanceChannelDetails, lowImportanceChannelDetails]);
}
  1. 发送通知
void _showNotification(FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin) async {
  var androidPlatformChannelSpecifics = AndroidNotificationDetails(
    'your_channel_id', // Channel ID (e.g., high_importance_channel)
    'Your channel name',
    'Your channel description',
    importance: Importance.high,
    priority: Priority.high,
    ticker: 'ticker',
    icon: '@mipmap/ic_launcher',
  );

  var iOSPlatformChannelSpecifics = IOSNotificationDetails(
    presentAlert: true,
    presentSound: true,
    presentBadge: true,
  );

  var platformChannelSpecifics = NotificationDetails(
    android: androidPlatformChannelSpecifics,
    iOS: iOSPlatformChannelSpecifics,
  );

  await flutterLocalNotificationsPlugin.show(
    0, // Notification ID
    'Hello', // Title
    'World', // Body
    platformChannelSpecifics,
    payload: 'item x',
  );
}

在你的应用逻辑中,你可以调用_showNotification函数来发送通知。

注意:

  • @mipmap/ic_launcher是Android应用的图标资源,你应该使用你自己的图标资源。
  • your_channel_id应该替换为你之前创建的通道ID,例如high_importance_channel

这段代码展示了如何在Flutter应用中初始化通知插件、创建通知渠道以及发送通知。希望这对你有所帮助!

回到顶部