Flutter:能否直接用AndroidNotification通过flutter_local_notifications展示通知?
问题解答
不行,没办法直接传入RemoteNotification或AndroidNotification对象给flutter_local_notifications来展示通知。
flutter_local_notifications有自己独立的类型体系,必须使用它提供的AndroidNotificationDetails(针对Android平台)和NotificationDetails(统一包装平台配置)对象来配置通知样式、行为等参数,才能调用展示方法。
你需要从Firebase的RemoteMessage里提取通知的相关字段(比如标题、内容、图标路径等),手动映射到AndroidNotificationDetails的对应属性中,再包装成NotificationDetails传入。举个简单的示例:
import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); FirebaseMessaging.onMessage.listen((RemoteMessage message) { print('Got a message whilst in the foreground!'); print('Message data: ${message.data}'); if (message.notification != null) { final RemoteNotification? notification = message.notification; final AndroidNotification? android = message.notification?.android; // 仅当Android端有通知数据时展示 if (notification != null && android != null) { // 创建flutter_local_notifications所需的Android配置 AndroidNotificationDetails androidDetails = AndroidNotificationDetails( 'your_channel_id', // 通知渠道ID,需提前创建 'your_channel_name', channelDescription: 'your_channel_description', icon: android.smallIcon, // 使用Firebase通知里的小图标 priority: Priority.high, importance: Importance.max, ); // 包装成统一的NotificationDetails NotificationDetails notificationDetails = NotificationDetails(android: androidDetails); // 展示通知 flutterLocalNotificationsPlugin.show( notification.hashCode, // 通知ID notification.title, notification.body, notificationDetails, payload: message.data['payload'], // 可选的自定义数据 ); } } });
简单来说,两个库的通知对象是不同类型,没有直接的兼容转换,必须手动提取字段构建目标对象才能完成展示。
内容的提问来源于stack exchange,提问作者Jiehfeng
相关产品推荐
相关产品推荐

