Flutter Firebase Cloud Messaging onMessage 被触发两次

Gus*_*Rue 8 firebase flutter firebase-cloud-messaging

我已经实现了 firebase_messaging flutter 包建议的基本配置。但是,每次我在我的颤振应用程序 onMessage 上收到通知时都会触发两次。我正在使用 firebase_messaging 6.0.9、Dart 2.7.0 和 Flutter 1.12.13+hotfix.5。

这是我的 [项目]/android/build.gradle

    buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
        classpath 'com.google.gms:google-services:4.3.2'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
   subprojects {
       project.buildDir = "${rootProject.buildDir}/${project.name}"
   }
   subprojects {
       project.evaluationDependsOn(':app')
   }

   task clean(type: Delete) {
       delete rootProject.buildDir
   }
Run Code Online (Sandbox Code Playgroud)

这是我的 [项目]/android/app/build.gradle

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 28

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.chat_notification"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}

apply plugin: 'com.google.gms.google-services'
Run Code Online (Sandbox Code Playgroud)

这是 onMessage 被触发两次的代码

import 'package:chat_notification/model/message.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';

class MessageWidget extends StatefulWidget {
  @override
  _MessageWidgetState createState() => _MessageWidgetState();
}

class _MessageWidgetState extends State<MessageWidget> {

  FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  List<Message> messages = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> response) async {
        print("onMessage: $response");
      },
      onLaunch: (Map<String, dynamic> response) async {
        print("onLaunch: $response");
      },
      onResume: (Map<String, dynamic> response) async {
        print("onResume: $response");
      },
    );
  }

  @override
  Widget build(BuildContext context) => ListView(
    children: messages.map(buildMessage).toList(),
  );

  Widget buildMessage(Message message) => ListTile(
    title: Text(message.title),
    subtitle: Text(message.body),
  );
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试创建新项目,但似乎每个项目都会发生。如果有人能帮助我解决这个问题,我将不胜感激。

编辑:

这在最新版本的 firebase_messaging: 7.0.0 中不再存在。我发现的最佳解决方案是更新包。不再存在重复的消息。

wer*_*tri 5

更新:

这在最新版本的 firebase_messaging(7.0.0 或更高版本)中不再存在。我发现的最佳解决方案是更新包。不再存在重复的消息。

原始解决方案:

我面临同样的问题。我不知道原因或解决方案。一个简单的方法是使用偶数计数器只捕获两个回调中的一个。

import 'package:chat_notification/model/message.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';

class MessageWidget extends StatefulWidget {
  @override
  _MessageWidgetState createState() => _MessageWidgetState();
}

class _MessageWidgetState extends State<MessageWidget> {

  FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  List<Message> messages = [];
  static int i = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> response) async {
        if(i%2==0) {
          print("onMessage: $response");
          // something else you wanna execute
        };
        i++;
      },
      onLaunch: (Map<String, dynamic> response) async {
        print("onLaunch: $response");
      },
      onResume: (Map<String, dynamic> response) async {
        print("onResume: $response");
      },
    );
  }

  @override
  Widget build(BuildContext context) => ListView(
    children: messages.map(buildMessage).toList(),
  );

  Widget buildMessage(Message message) => ListTile(
    title: Text(message.title),
    subtitle: Text(message.body),
  );
}
Run Code Online (Sandbox Code Playgroud)

这将只运行一次代码!类似地可用于 onLaunch 和 onResume。

  • 具有相同意义的一点改进: static bool _isDoubleMessage = false; onMessage: (Map&lt;String,dynamic&gt; message) async { if(!_isDoubleMessage) { print('on message $message'); } //setState(() =&gt; _message = message["notification"]["title"]); } _isDoubleMessage = !_isDoubleMessage; }, (2认同)