You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase Messaging发送1条通知却收到2条的问题求助

FCM推送重复接收问题求助

我在使用Firebase Messaging时遇到异常:无论是通过Firebase控制台还是后台调用FCM接口发送通知,明明仅发送1条,客户端却会收到2条推送。我尝试过部分解决方案但均无效,想请教是否有开发者遇到过类似情况,以下是我的实现代码:

文件夹结构

custom_firebase_messaging.dart

class CustomFirebaseMessaging {
  final CustomLocalNotification _customLocalNotification;
  
  CustomFirebaseMessaging._internal(this._customLocalNotification);
  static final CustomFirebaseMessaging _singleton = CustomFirebaseMessaging._internal(CustomLocalNotification());
  factory CustomFirebaseMessaging() => _singleton;

  Future<void> inicialize() async {
    await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(badge: true, sound: true, alert: true);

    FirebaseMessaging.onMessage.listen((message) {
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;

      if (notification != null && android != null) {
        _customLocalNotification.androidNotification(notification, android);
      }
    });

    FirebaseMessaging.onMessageOpenedApp.listen((message) {
      if (message.data['route'] != null) {
        NavigationService.navigatorKey.currentState?.pushNamed(message.data['route']);
      }
    });
  }
}

custom_local_notification.dart

class CustomLocalNotification {
  late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
  late AndroidNotificationChannel channel;

  CustomLocalNotification() {
    channel = const AndroidNotificationChannel(
      'high_importance_channel',
      'High Importance Notifications',
      description: 'This channel is used for important notifications',
      importance: Importance.max,
    );

    _configureAndroid().then(
      (value) {
        flutterLocalNotificationsPlugin = value;
        inicializeNotifications();
      },
    );
  }

  Future<FlutterLocalNotificationsPlugin> _configureAndroid() async {
    final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
    await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);

    return flutterLocalNotificationsPlugin;
  }

  Future<void> inicializeNotifications() async {
    const android = AndroidInitializationSettings('@mipmap/ic_launcher');
    await flutterLocalNotificationsPlugin.initialize(
      const InitializationSettings(android: android),
    );
  }

  Future<void> androidNotification(
      RemoteNotification notification, AndroidNotification android) async {
    await flutterLocalNotificationsPlugin.show(
      notification.hashCode,
      notification.title,
      notification.body,
      NotificationDetails(
        android: AndroidNotificationDetails(
          channel.id,
          channel.name,
          channelDescription: channel.description,
          icon: android.smallIcon,
        ),
      ),
    );
  }
}

startup.dart

@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  log("Handling a background message: ${message.messageId}");
}

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

    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );

    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    await CustomFirebaseMessaging().inicialize();

    FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterFatalError;

    runApp(const App());
  }, (error, stack) => FirebaseCrashlytics.instance.recordError(error, stack));
}

FCM发送实现代码

void sendPushMessage(String title, String body, String token) async {
    try {
      await Dio().post(
        'https://fcm.googleapis.com/fcm/send',
        options: Options(
          headers: <String, String>{
            'Content-Type': 'application/json',
            'Authorization':
                'myKey',
          },
        ),
        data: jsonEncode(
          <String, dynamic>{
            "to": token,
            "notification": {
              "title": title,
              "body": body,
            },
            "data": {
              "channelId": "session_alert",
            }
          },
        ),
      );
    } catch (e) {
      log("Error push notification");
    }
  }

尝试过的无效方案(导致无法发送消息)

{
"to" : user_token,
"notificaton": {}, // 移除这个字段
"data" : {
    "channelId":"session_alert",
    "title":"message title",
    "body":"message body",
}
}

内容的提问来源于stack exchange,提问作者I. Biraj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 02:45:39