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

配置Firebase Cloud Messaging后Flutter Android APK无法运行求助

Flutter集成Firebase Cloud Messaging后APK无法运行

我用Flutter开发Android应用,最初APK能正常运行,但配置Firebase Cloud Messaging(仅修改了pubspec.yaml和相关.dart源码)后,生成的APK无法正常工作。

已尝试以下操作但均无效:

  • 清理/修复Dart缓存
  • 执行flutter pub get/flutter pub upgrade/flutter pub outdated命令
  • 重置缓存
  • 重装Android Studio
  • 创建新Flutter项目测试
  • 手动修改pubspec.yaml依赖版本
  • 重装Flutter SDK

项目相关文件

1. android\app\src\main\AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application
        android:label="studioc5"
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            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">
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
    <queries>
        <intent>
            <action android:name="android.intent.action.PROCESS_TEXT"/>
            <data android:mimeType="text/plain"/>
        </intent>
    </queries>
</manifest>

2. GeneratedPluginRegistrant.java

package io.flutter.plugins;

import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import io.flutter.Log;

import io.flutter.embedding.engine.FlutterEngine;

@Keep
public final class GeneratedPluginRegistrant {
  private static final String TAG = "GeneratedPluginRegistrant";
  public static void registerWith(@NonNull FlutterEngine flutterEngine) {
    try {
      flutterEngine.getPlugins().add(new io.flutter.plugins.firebase.core.FlutterFirebaseCorePlugin());
    } catch (Exception e) {
      Log.e(TAG, "Error registering plugin firebase_core, io.flutter.plugins.firebase.core.FlutterFirebaseCorePlugin", e);
    }
    try {
      flutterEngine.getPlugins().add(new io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingPlugin());
    } catch (Exception e) {
      Log.e(TAG, "Error registering plugin firebase_messaging, io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingPlugin", e);
    }
  }
}

3. app/build.gradle

plugins {
    id "com.android.application"
    id "kotlin-android"
    id "dev.flutter.flutter-gradle-plugin"
}

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

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

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

android {
    namespace "com.example.studioc5"
    compileSdk flutter.compileSdkVersion
    ndkVersion flutter.ndkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        applicationId "com.example.studioc5"
        minSdkVersion flutter.minSdkVersion
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    buildTypes {
        release {
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {}

4. pubspec.yaml 依赖部分

cupertino_icons: 1.0.6
firebase_messaging: 14.7.4
firebase_core: 2.27.0
http: 1.2.0
rounded_expansion_tile: 0.0.13

5. main.dart 核心代码

void main() async {
       await Firebase.initializeApp(
       options: DefaultFirebaseOptions.currentPlatform,
  );

  runApp(const MyHomePage());
}

排查与解决方法

  1. 确认Firebase配置文件
    检查google-services.json是否正确放在android/app目录下,且文件内的package_name与app/build.gradle中的applicationId完全一致。

  2. 添加Firebase Gradle插件
    在项目根目录的build.gradle中添加Google服务依赖:

    buildscript {
        dependencies {
            classpath 'com.google.gms:google-services:4.4.1'
        }
    }
    

    再在app/build.gradle末尾添加:

    apply plugin: 'com.google.gms.google-services'
    
  3. 统一依赖版本
    当前firebase_messaging与firebase_core版本兼容性存疑,建议升级到匹配的最新版本,比如:

    firebase_core: ^2.27.0
    firebase_messaging: ^14.7.17
    

    执行flutter pub get后重新构建。

  4. 抓取错误日志
    连接设备后执行adb logcat *:E,过滤错误日志,重点查找Firebase初始化相关的异常(如API密钥错误、配置缺失)。

  5. 补充必要权限
    在AndroidManifest中添加FCM所需权限:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    
  6. 重新生成Firebase配置
    若手动修改过配置,执行flutterfire configure命令重新生成DefaultFirebaseOptions,确保参数正确。


内容的提问来源于stack exchange,提问作者noblesseoblige

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 03:24:55