Flutter firebase_消息onBackgroundMessage本地_通知

Flutter firebase_消息onBackgroundMessage本地_通知,flutter,push-notification,firebase-cloud-messaging,Flutter,Push Notification,Firebase Cloud Messaging,当应用程序关闭或处于后台时,我试图从firebase_消息中停止默认通知 我想在应用程序关闭时或在后台使用local_notifications插件显示自定义通知,该插件按预期工作,问题在消息发送时存在,应用程序显示相同的通知两次,默认情况下显示一次通知,另一次显示自定义通知 我无法实现停止默认通知。有人能指出我的错误吗 初始代码来自firebase消息传递示例,用于删除不必要的代码段和添加自定义通知 还附上了当前的图像(不良行为) 如前所述,同一个通知显示了两次,希望删除图像上显示的第一个通

当应用程序关闭或处于后台时,我试图从firebase_消息中停止默认通知

我想在应用程序关闭时或在后台使用local_notifications插件显示自定义通知,该插件按预期工作,问题在消息发送时存在,应用程序显示相同的通知两次,默认情况下显示一次通知,另一次显示自定义通知

我无法实现停止默认通知。有人能指出我的错误吗

初始代码来自firebase消息传递示例,用于删除不必要的代码段和添加自定义通知

还附上了当前的图像(不良行为)

如前所述,同一个通知显示了两次,希望删除图像上显示的第一个通知

这是我的密码:

// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

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

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  print('_firebaseMessagingBackgroundHandler');

  Future onDidReceiveLocalNotification(
      int? id, String? title, String? body, String? payload) async {
    print('onDidReceiveLocalNotification');
  }

  final channel = AndroidNotificationChannel(
    'high_importance_channel', // id
    'High Importance Notifications', // title
    'This channel is used for important notifications.', // description
    importance: Importance.high,
  );

  var flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  final initializationSettingsAndroid =
      AndroidInitializationSettings('icon_app');
  final initializationSettingsIOS = IOSInitializationSettings(
      onDidReceiveLocalNotification: onDidReceiveLocalNotification);
  final initializationSettingsMacOS = MacOSInitializationSettings();

  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);
  final initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
      macOS: initializationSettingsMacOS);
  await flutterLocalNotificationsPlugin.initialize(
    initializationSettings,
    onSelectNotification: onSelectNotification,
  );

  ///Not able to stop default notification
  ///there fore when custom notification is called
  ///result is 2 notifications displayed.
  NotificationDetails _notificationDetails;
  _notificationDetails = await customNotification(message: message);
  flutterLocalNotificationsPlugin.show(
    message.notification.hashCode,
    message.notification!.title,
    message.notification!.body,
    _notificationDetails,
    payload: '',
  );

  // await Firebase.initializeApp();
  print('Handling a background message ${message.messageId}');
}

Future<NotificationDetails> customNotification(
    {required RemoteMessage message}) async {
  print('notificationDetailsBigImage');
  final utils = Utils();

  final bigPicturePath = await utils.downloadAndSaveFile(
      url: 'https://picsum.photos/536/354', fileName: 'bigPicture');
  final bigPictureStyleInformation = BigPictureStyleInformation(
    FilePathAndroidBitmap(bigPicturePath),
    hideExpandedLargeIcon: true,
  );
  final androidPlatformChannelSpecifics = AndroidNotificationDetails(
    'big text channel name',
    'big text channel name',
    'big text channel description',
    styleInformation: bigPictureStyleInformation,
    icon: 'icon_app',
    color: const Color.fromARGB(255, 255, 0, 0),
    ledColor: const Color.fromARGB(255, 255, 0, 0),
    ledOnMs: 1000,
    ledOffMs: 500,
  );
  return NotificationDetails(android: androidPlatformChannelSpecifics);
}

Future<void> onDidReceiveLocalNotification(
    int? id, String? title, String? body, String? payload) async {
  print('onDidReceiveLocalNotification');
}

Future<void> onSelectNotification(String? payload) async {
  print('onSelectNotification');
}

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
    alert: true,
    badge: true,
    sound: true,
  );

  runApp(MessagingExampleApp());
}

/// Entry point for the example application.
class MessagingExampleApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Messaging Example App',
      theme: ThemeData.dark(),
      routes: {
        '/': (context) => Application(),
      },
    );
  }
}

/// Renders the example application.
class Application extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _Application();
}

class _Application extends State<Application> {
  late String _token;

  @override
  void initState() {
    super.initState();
    FirebaseMessaging.instance.getInitialMessage().then((message) {
      print('instance');
      if (message != null) {
        print('do stuff');
      }
    });

    FirebaseMessaging.onMessage.listen((message) {
      print('onMessage');
    });

    FirebaseMessaging.onMessageOpenedApp.listen((message) {
      print('A new onMessageOpenedApp event was published!');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold();
  }
}
//作者版权所有。版权所有。
//此源代码的使用受BSD样式许可证的约束,该许可证可以
//在许可证文件中找到。
导入“dart:async”;
导入“包:firebase_core/firebase_core.dart”;
导入“package:firebase_messaging/firebase_messaging.dart”;
进口“包装:颤振/材料.省道”;
导入“package:flatter_local_notifications/flatter_local_notifications.dart”;
导入“utils/utils.dart”;
Future\u firebaseMessagingBackgroundHandler(远程消息)异步{
打印(“firebaseMessagingBackgroundHandler”);
未来onDidReceiveLocalNotification(
int?id、String?title、String?body、String?payload)异步{
打印(“onDidReceiveLocalNotification”);
}
最终通道=AndroidNotificationChannel(
“高重要性通道”,//id
“高重要性通知”,//标题
“此通道用于重要通知。”,//说明
重要性:重要性,
);
var flatterLocalNotificationsPlugin=flatterLocalNotificationsPlugin();
最终初始化设置和ROID=
AndroidInitializationSettings(“图标应用程序”);
最终初始化设置SIOS=IOSSInitializationSettings(
onDidReceiveLocalNotification:onDidReceiveLocalNotification);
最终初始化设置SMACOS=MacOSInitializationSettings();
等待通知
.resolvePlatformSpecificImplementation<
AndroidLutterLocalNotificationsPlugin>()
?createNotificationChannel(频道);
最终初始化设置=初始化设置(
android:initializationSettingsAndroid,
iOS:初始化设置SIOS,
macOS:初始化设置SMACOS);
等待本地通知splugin.initialize(
初始化设置,
onSelectNotification:onSelectNotification,
);
///无法停止默认通知
///因此,当调用自定义通知时
///结果显示2个通知。
通知详情(NotificationDetails);;
_notificationDetails=等待定制通知(消息:消息);
flatterLocalNotificationsPlugin.show(
message.notification.hashCode,
message.notification!.title,
message.notification!.body,
_通知详情,
有效载荷:“”,
);
//等待Firebase.initializeApp();
打印('处理背景消息${message.messageId}');
}
未来海关通知(
{必需的RemoteMessage})异步{
打印('NotificationDetailsGimage');
最终utils=utils();
final bigPicturePath=wait utils.download和savefile(
网址:'https://picsum.photos/536/354,文件名:“bigPicture”);
最终bigPictureStyleInformation=bigPictureStyleInformation(
FilePathAndroidBitmap(bigPicturePath),
hideExpandedLargeIcon:true,
);
最终androidPlatformChannelSpecifics=AndroidNotificationDetails(
“大文本频道名称”,
“大文本频道名称”,
“大文本频道说明”,
styleInformation:bigPictureStyleInformation,
图标:“图标应用程序”,
颜色:const color.fromARGB(255,255,0,0),
ledColor:const Color.fromARGB(255,255,0,0),
ledOnMs:1000,
列席人员:500人,
);
返回通知详细信息(android:androidPlatformChannelSpecifics);
}
未来onDidReceiveLocalNotification(
int?id、String?title、String?body、String?payload)异步{
打印(“onDidReceiveLocalNotification”);
}
未来onSelectNotification(字符串?有效负载)异步{
打印(“onSelectNotification”);
}
Future main()异步{
WidgetsFlutterBinding.ensureInitialized();
等待Firebase.initializeApp();
FirebaseMessagingBackgroundMessage(_firebaseMessagingBackgroundHandler);
等待FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
警报:是的,
徽章:没错,
听起来:是的,
);
runApp(MessagineXampleApp());
}
///示例应用程序的入口点。
类MessagineXampleApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回材料PP(
标题:“消息传递示例应用程序”,
主题:ThemeData.dark(),
路线:{
“/”:(上下文)=>Application(),
},
);
}
}
///呈现示例应用程序。
类应用程序扩展StatefulWidget{
@凌驾
State createState()=>u应用程序();
}
类应用程序扩展状态{
延迟字符串_标记;
@凌驾
void initState(){
super.initState();
FirebaseMessaging.instance.getInitialMessage().then((消息){
打印(“实例”);
如果(消息!=null){
打印(“做事情”);
}
});
FirebaseMessaging.onMessage.listen((消息){
打印(“onMessage”);
});
FirebaseMessaging.onMessageGeoPenedApp.listen((消息){
print('发布了新的OnMessagePointedApp事件!');
});
}
@凌驾
小部件构建(构建上下文){
返回脚手架();
}
}

好的,这是我这边的错误。在阅读FCM文档之后,似乎有两种类型的FCM推送:通知和数据

通知具有默认行为,即显示当前默认推送通知。设置时
"token"=> "...."    
"data" => ["notificationDisplay" => "bigImage"],
            "notification" => [ //<-- this will trigger a Push notification
               "title" => $title,
               "body" => $message,
             ],
            ...
"token"=> "...."    
"data" => ["notificationDisplay" => "bigImage"],
// without notification on payload will trigger 
//Data Message, as expected you will need to declare 
//all fields you logic expects on data structure.