Flutter firebase_messaging android app crash on .getToken() call

2,322

Solution 1

For me, it worked by downgrading from

com.google.firebase:firebase-bom:28.0.1

to

com.google.firebase:firebase-bom:27.0.0

Hint: this is a temporary solution for those versions:

firebase_messaging: ^9.1.4 firebase_core: ^1.1.1

Solution 2

Solution

For some reason I had put the onBackgroundMessageHandler as a class method in my project. The problem were resolved by simply placing the method as a top-level function as it should be.

Before

class MyNotificationClass {
      Future<dynamic> onBackgroundMessageHandler(RemoteMessage message) async {
        print('on Background $message');
      }

      // ...
    }

After

Future<dynamic> onBackgroundMessageHandler(RemoteMessage message) async {
            print('on Background $message');
          }

class MyNotificationClass {
          // ...
        }

android -> app -> src -> build.gradle

dependencies {
    implementation 'com.google.android.material:material:1.3.0'
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    // Import the Firebase BoM
    implementation platform('com.google.firebase:firebase-bom:26.3.0')

    // Add the dependency for the Firebase SDK for Google Analytics
    // When using the BoM, don't specify versions in Firebase dependencies
    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.google.firebase:firebase-auth'
    implementation 'com.google.firebase:firebase-messaging'
}
// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'

android -> build.gradle

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        //classpath 'com.android.tools.build:gradle:4.1.0'
        classpath 'com.android.tools.build:gradle:3.5.3' // 3.5.0
        classpath 'com.google.gms:google-services:4.3.2' // 4.3.2
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

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

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

task clean(type: Delete) {
    delete rootProject.buildDir
}

pubspec.yaml

  cloud_firestore: ^1.0.5 #^0.14.4 #^0.13.5                     
  firebase_database: ^6.1.2 #4.4.0                             
  firebase_core: ^1.0.3 #^0.5.3 #^0.4.4+3                       
  firebase_auth: ^1.1.0 #0.18.4+1 #^0.16.0                     
  firebase_messaging: ^9.1.1 #7.0.3 #^6.0.15                   
  firebase_dynamic_links: ^2.0.0 #0.6.3 #^0.5.0+11             
  firebase_analytics: ^8.0.0 #6.3.0 #^5.0.11                   
  cloud_functions: ^1.0.3 #0.7.2 #^0.5.0                       

AndroidManifest.xml

<application
        android:name=".Application"
        android:label="app name"
        android:usesCleartextTraffic="true"
        android:icon="@mipmap/ic_launcher">

        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
                android:name="io.flutter.embedding.android.NormalTheme"
                android:resource="@style/NormalTheme"
                />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
                android:name="io.flutter.embedding.android.SplashScreenDrawable"
                android:resource="@drawable/launch_background"
                />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>

            <intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@mipmap/ic_notification" />

        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
Share:
2,322
CoffeeSnus
Author by

CoffeeSnus

Updated on November 27, 2022

Comments

  • CoffeeSnus
    CoffeeSnus over 1 year

    I'm trying to integrate firebase_messaging package with my flutter app. Usually it works(version 7.0.3) fine with the code I'm using(see below) but since the null-safety version was released my code doesn't work anymore. I wonder if someone could help me to find out what I'm doing wrong?

    Error causing code

    try {
        fcmToken = await _firebaseMessaging.getToken();
    } catch (error) {
        print(error);
    }
    

    Error output

    E/AndroidRuntime( 8942): java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/iid/Metadata;
    E/AndroidRuntime( 8942):    at io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingPlugin.lambda$getToken$1$FlutterFirebaseMessagingPlugin(FlutterFirebaseMessagingPlugin.java:165)
    E/AndroidRuntime( 8942):    at io.flutter.plugins.firebase.messaging.-$$Lambda$FlutterFirebaseMessagingPlugin$p8YQXDuFBNIxl8PFaPCQJtYc3sw.call(Unknown Source:4)
    E/AndroidRuntime( 8942):    at com.google.android.gms.tasks.zzv.run(Unknown Source:2)
    E/AndroidRuntime( 8942):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    E/AndroidRuntime( 8942):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    E/AndroidRuntime( 8942):    at java.lang.Thread.run(Thread.java:923)
    E/AndroidRuntime( 8942): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.iid.Metadata" on path: DexPathList[[zip file "/data/app/~~uCa7QFzhvu5i_TZpnqat0w==/com.example.****-1cbY-LKuCoOsfZybV-Gq6g==/base.apk"],nativeLibraryDirectories=[/data/app/~~uCa7QFzhvu5i_TZpnqat0w==/com.example.****-1cbY-LKuCoOsfZybV-Gq6g==/lib/x86, /data/app/~~uCa7QFzhvu5i_TZpnqat0w==/com.example.****-1cbY-LKuCoOsfZybV-Gq6g==/base.apk!/lib/x86, /system/lib, /system_ext/lib]]
    E/AndroidRuntime( 8942):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:207)
    E/AndroidRuntime( 8942):    at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
    E/AndroidRuntime( 8942):    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    E/AndroidRuntime( 8942):    ... 6 more
    

    app -> src -> main -> kotlin -> Application.kt

    import io.flutter.app.FlutterApplication
    import io.flutter.plugin.common.PluginRegistry
    
    import io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingPlugin
    
    class Application() : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
        override fun registerWith(registry: PluginRegistry?) {
            val key: String? = FlutterFirebaseMessagingPlugin::class.java.canonicalName
            if (!registry?.hasPlugin(key)!!) {
                FlutterFirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingPlugin"));
            }
        }
    }
    

    app -> src -> main -> kotlin -> MainActivity.kt

    import androidx.annotation.NonNull;
    import io.flutter.embedding.android.FlutterActivity
    import io.flutter.embedding.engine.FlutterEngine
    import io.flutter.plugins.GeneratedPluginRegistrant
    
    class MainActivity: FlutterActivity() {
        override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
            GeneratedPluginRegistrant.registerWith(flutterEngine);
        }
    }
    
  • Eibo
    Eibo almost 3 years
    I'm having the same issue, I'm not using onBackgroundMessageHandler at all and yet I'm getting the same crash
  • CoffeeSnus
    CoffeeSnus almost 3 years
    Hmm. I can post my configuration files and you can try to edit your files and see if it works? Hope it helps.
  • Eibo
    Eibo almost 3 years
    It worked by downgrading from com.google.firebase:firebase-bom:28.0.1 to 27.0.0
  • CoffeeSnus
    CoffeeSnus almost 3 years
    Nice! I'm glad you managed to solve it. Happy coding!
  • emanuel sanga
    emanuel sanga almost 3 years
    I think bom28 is buggy, plus getToken needs vapidKey now. Not seeing that in bom26
  • Suat Özkaya
    Suat Özkaya almost 3 years
    Downgrading to 27.0.0 also solved my problem. Thanks.
  • 瀧谷賢司
    瀧谷賢司 over 2 years
    My problem was with react.js, but replacing the library with 27.0.0 certainly fixed it. Thank you.