我正在使用 flutter Awesome 通知,每当我从 firebase 发送通知或从我的自定义后端发送通知时,我都会收到两个通知,一个没有操作按钮,一个有操作按钮,我还尝试删除操作按钮以检查这是否导致问题但仍然收到相同的重复通知
这是我的 main.dart 文件,我在其中完成了通知初始化:
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
if (message.notification != null) {
// log(message.data["notification_id"]);
NotificationService.showNotification(
title: message.notification!.title!,
body: message.notification!.body!,
actionButtons: actionButtons);
}
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
}
GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
final actionButtons = [
NotificationActionButton(
key: 'Verify',
label: 'Confirm Now',
enabled: true,
),
];
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final id = await cGetDeviceId();
CommonData.deviceId = id;
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
await NotificationService.initializeNotification();
FirebaseMessaging messagingg = FirebaseMessaging.instance;
FirebaseMessaging.instance.getInitialMessage().then((value) {
if (value?.notification != null) {
// log(value!.data["notification_id"]);
NotificationService.showNotification(
title: value!.notification!.title!,
body: value.notification!.body!,
actionButtons: actionButtons);
}
});
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
await messagingg.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
sound: true,
);
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
if (message.notification != null) {
// log(message.data["notification_id"]);
NotificationService.showNotification(
title: message.notification!.title!,
body: message.notification!.body!,
actionButtons: actionButtons);
}
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
if (message.notification != null) {
// log(message.data["notification_id"]);
NotificationService.showNotification(
title: message.notification!.title!,
body: message.notification!.body!,
actionButtons: actionButtons);
}
});
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider<LoadingManagemet>(
create: (context) => LoadingManagemet(),
),
ChangeNotifierProvider<ParkingRemindersSingleton>(
create: (context) => ParkingRemindersSingleton(),
),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Ay Caramba',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const SplashScreen(),
));
}
}
这是我的通知服务文件:
import 'dart:developer';
import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:flutter/material.dart';
class NotificationService {
static Future<void> initializeNotification() async {
await AwesomeNotifications().initialize(
null,
[
NotificationChannel(
channelGroupKey: 'high_importance_channel',
channelKey: 'high_importance_channel',
channelName: 'Basic notifications',
channelDescription: 'Notification channel for basic tests',
defaultColor: const Color(0xFF9D50DD),
ledColor: Colors.white,
importance: NotificationImportance.Max,
channelShowBadge: true,
onlyAlertOnce: true,
playSound: true,
criticalAlerts: true,
)
],
channelGroups: [
NotificationChannelGroup(
channelGroupKey: 'high_importance_channel_group',
channelGroupName: 'Group 1',
)
],
debug: true,
);
await AwesomeNotifications().isNotificationAllowed().then(
(isAllowed) async {
if (!isAllowed) {
await AwesomeNotifications().requestPermissionToSendNotifications();
}
},
);
await AwesomeNotifications().setListeners(
onActionReceivedMethod: onActionReceivedMethod,
onNotificationCreatedMethod: onNotificationCreatedMethod,
onNotificationDisplayedMethod: onNotificationDisplayedMethod,
onDismissActionReceivedMethod: onDismissActionReceivedMethod,
);
}
/// Use this method to detect when a new notification or a schedule is created
static Future<void> onNotificationCreatedMethod(
ReceivedNotification receivedNotification) async {
debugPrint('onNotificationCreatedMethod');
}
/// Use this method to detect every time that a new notification is displayed
static Future<void> onNotificationDisplayedMethod(
ReceivedNotification receivedNotification) async {
debugPrint('onNotificationDisplayedMethod');
}
/// Use this method to detect if the user dismissed a notification
static Future<void> onDismissActionReceivedMethod(
ReceivedAction receivedAction) async {
debugPrint('onDismissActionReceivedMethod');
}
/// Use this method to detect when the user taps on a notification or action button
static Future<void> onActionReceivedMethod(
ReceivedAction receivedAction) async {
debugPrint('onActionReceivedMethod');
final payload = receivedAction.toString();
// final notificationId = payload['notification_id'];
log('Notification ID: $payload');
}
static Future<void> showNotification({
required final String title,
required final String body,
final String? summary,
final Map<String, String>? payload,
final ActionType actionType = ActionType.Default,
final NotificationLayout notificationLayout = NotificationLayout.Default,
final NotificationCategory? category,
final String? bigPicture,
final List<NotificationActionButton>? actionButtons,
final bool scheduled = false,
final int? interval,
}) async {
assert(!scheduled || (scheduled && interval != null));
await AwesomeNotifications().createNotification(
content: NotificationContent(
id: -1,
channelKey: 'high_importance_channel',
title: title,
body: body,
actionType: actionType,
notificationLayout: notificationLayout,
summary: summary,
category: category,
payload: payload,
bigPicture: bigPicture,
),
actionButtons: actionButtons,
schedule: scheduled
? NotificationInterval(
interval: interval,
timeZone:
await AwesomeNotifications().getLocalTimeZoneIdentifier(),
preciseAlarm: true,
)
: null,
);
}
}
我需要帮助来解决这个问题,并希望实现像当用户单击操作按钮时 notification_id 登录到控制台一样,所以我将使用它来在 API 命中中利用。
我有同样的问题,我认为在后台,很棒的通知会自动处理发送通知,这就是为什么你收到两个通知,第一个是由很棒的通知处理的,第二个是由你在 firebase onbackground 消息处理程序中处理的,到目前为止我已经找不到任何解决方案。