通知在 flutter 上显示两次

问题描述 投票:0回答:4

我被困住了。我的后台通知显示两次。但前台只有一个通知。这是我的代码

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // If you're going to use other Firebase services in the background, such as Firestore,
  // make sure you call `initializeApp` before using other Firebase services.
  await Firebase.initializeApp();
  if(
      !AwesomeStringUtils.isNullOrEmpty(message.notification?.title, considerWhiteSpaceAsEmpty: true) ||
      !AwesomeStringUtils.isNullOrEmpty(message.notification?.body, considerWhiteSpaceAsEmpty: true)
    ){
      // print('message also contained a notification: ${message.notification.body}');
      
      String imageUrl;
      imageUrl ??= message.notification.android?.imageUrl;
      imageUrl ??= message.notification.apple?.imageUrl;
      print(imageUrl);
      if(imageUrl == null){
        var id = Random().nextInt(2147483647);
        await AwesomeNotifications().createNotification(
          content: NotificationContent(
            id: id,
            title: message.notification.title,
            body: message.notification.body,
            color: Colors.orange,
            customSound: 'resource://raw/alert',
            notificationLayout: NotificationLayout.BigText,
            channelKey: 'basic_channel_background',
            payload: {'data':message.data['payload']}
          ),
          actionButtons: [
            NotificationActionButton(
              label: 'Lihat Selengkapnya',
              enabled: true,
              buttonType: ActionButtonType.Default,
              key: 'background',
            )
          ]
        );
      }else{
        await AwesomeNotifications().createNotification(
          content: NotificationContent(
            id: Random().nextInt(2147483647),
            title: message.notification.title,
            body: message.notification.body,
            bigPicture: imageUrl,
            color: Colors.orange,
            customSound: 'resource://raw/alert',
            notificationLayout: NotificationLayout.BigPicture,
            channelKey: 'basic_channel_background',
            payload: {'data':message.data['payload']}
          ),
          actionButtons: [
            NotificationActionButton(
              label: 'Lihat Selengkapnya',
              enabled: true,
              buttonType: ActionButtonType.Default,
              key: 'background',
            )
          ]
        );
      }
    }
}
// End Background Message

这是我的前台代码

// Foreground Apps
Future<void> main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  if (!kIsWeb) {
    await FirebaseMessaging.instance
        .setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );
    await AwesomeNotifications().initialize(
    'resource://mipmap/launcher_icon',
    [
      NotificationChannel(
          channelGroupKey: 'basic_tests',
          channelKey: 'basic_channel',
          channelName: 'My Cahaya Notification',
          channelDescription: 'Notification channel for basic tests',
          icon: 'resource://mipmap/launcher_icon',
          importance: NotificationImportance.High,
          playSound: true,
          soundSource: 'resource://raw/alert'
      ),
       NotificationChannel(
          channelGroupKey: 'basic_background',
          channelKey: 'basic_channel_background',
          channelName: 'My Cahaya Notification Background',
          channelDescription: 'Notification channel for basic tests',
          icon: 'resource://mipmap/launcher_icon',
          importance: NotificationImportance.High,
          playSound: true,
          soundSource: 'resource://raw/alert'
      ),
    ], debug: true);
    AwesomeNotifications().actionStream.listen((event) async{
      print('event received!');
      var data = event.toMap();
      if(data['buttonKeyPressed'] == "background"){
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString("Navigate", data['payload']['data']);
      }else{
        _navigateToItemForeground(data['payload']['data']);  
      }
      // do something based on event...
      // AwesomeNotifications().actionSink.close();
    });
  } 
  
   FirebaseMessaging.onMessage.listen((RemoteMessage message) async{
      RemoteNotification notification = message.notification;
      AndroidNotification android = message.notification?.android;
      if (notification != null && android != null && !kIsWeb) {
        if(!AwesomeStringUtils.isNullOrEmpty(message.notification?.title, considerWhiteSpaceAsEmpty: true) ||
        !AwesomeStringUtils.isNullOrEmpty(message.notification?.body, considerWhiteSpaceAsEmpty: true)){
        print("something");

        String imageUrl;
        imageUrl ??= notification.android?.imageUrl;
        imageUrl ??= notification.apple?.imageUrl;
        
        if(imageUrl == null){
          await AwesomeNotifications().createNotification(
            content: NotificationContent(
              id: Random().nextInt(2147483647),
              title: notification.title,
              body: notification.body,
              color: Colors.orange,
              customSound: 'resource://raw/alert',
              notificationLayout: NotificationLayout.BigText,
              channelKey: 'basic_channel',
              payload: {'data':message.data['payload']}
            ),
            actionButtons: [
              NotificationActionButton(
                label: 'Lihat Selengkapnya',
                enabled: true,
                buttonType: ActionButtonType.Default,
                key: 'test',
              )
            ]
          );
        }else{
          await AwesomeNotifications().createNotification(
            content: NotificationContent(
              id: Random().nextInt(2147483647),
              title: notification.title,
              body: notification.body,
              bigPicture: imageUrl,
              color: Colors.orange,
              customSound: 'resource://raw/alert',
              notificationLayout: NotificationLayout.BigPicture,
              channelKey: 'basic_channel',
              payload: {'data':message.data['payload']}
            ),
            actionButtons: [
              NotificationActionButton(
                label: 'Lihat Selengkapnya',
                enabled: true,
                buttonType: ActionButtonType.Default,
                key: 'test',
              )
            ]
          );
        }
      }
    }
  });
  runApp(MyApp());
}
// End Foreground Apps

这是我的屏幕截图 截图

我尝试更改很棒的通知,但结果是相同的。你能帮我解决这个问题吗?我希望你能帮助我。非常感谢你

android firebase flutter
4个回答
15
投票

如果您的通知是在应用程序处于后台时发送的,Firebase 自动发送推送通知,因此您无需在应用程序中手动调用显示通知。

我是这样解决问题的:

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  if (message.notification != null) {
    //No need for showing Notification manually. 
    //For BackgroundMessages: Firebase automatically sends a Notification.
    //If you call the flutterLocalNotificationsPlugin.show()-Methode for
    //example the Notification will be displayed twice.
  }
  return;
}

13
投票

FCM 有效负载


{
    "to":"_some_fcm_token_",
    //remove this
    "notification": {
        "title": "this is title",
        "body": "this is subtitle"
    },
    "type": "post_like",
    "data": {
        "model":{"id":"dsaflkdskfklgdkgjdksakdk"},
        "body": "this is subtitle",
        "title": "this is title",
        "click_action": "FLUTTER_NOTIFICATION_CLICK"
    },
    "priority": "normal"
}

第一个是手动创建的(本地),另一个是 Firebase 自动创建的。

向您的设备发送消息时,请确保该消息是

notification
而不是
data
文档提到,如果您发送数据,它可能会作为推送通知被忽略。仅使用它来向应用程序发送数据包。


0
投票

有效负载:Platform.isAndroid? json.encode(message.data):json.encode(message.notification)

像这样设置有效负载数据


0
投票

这是因为您初始化了

await Firebase.initializeApp()
两次,一次用于 Background,另一次用于 Foreground。去掉后台初始化就可以正常工作了。

© www.soinside.com 2019 - 2024. All rights reserved.