簡體   English   中英

Flutter Web - No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app)

[英]Flutter Web - No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app)

我知道有很多與此非常相似的問題; 但他們的解決方案都不適合我。 我都試過了。 PS:我希望問題與我的索引有關。html

問題:我正在使用 Firebase(在 Flutter 網絡上),我正在嘗試通過它對用戶進行身份驗證。 但是,在我嘗試將 Firebase 添加到它以使其正常工作后,我的網站甚至無法啟動(空白屏幕)。 我會很感激一些幫助解決這個問題!

錯誤:沒有 Firebase App '[DEFAULT]' has created - call Firebase App.initializeApp() (app/no-app)

注意:問題出現在 Flutter web 但在我的 Android 手機上有效。 此外,我花了幾個小時查找所有類似問題的每個答案,但他們的解決方案都不起作用。 另外,這是我第一次提出問題,所以如果我做錯了什么,請告訴我。 謝謝!

Output 錯誤:

To hot restart changes while running, press "r" or "R".
For a more detailed help message, press "h". To quit, press "q".
FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()
(app/no-app).
    at Object.u [as app] (https://www.gstatic.com/firebasejs/8.4.3/firebase-app.js:1:18229)
    at Object.app$ [as app]
    (http://localhost:60058/packages/firebase_core_web/src/interop/core.dart.lib.js:42:101)
    at new cloud_firestore_web.FirebaseFirestoreWeb.new
    (http://localhost:60058/packages/cloud_firestore_web/src/write_batch_web.dart.lib.js:865:64)
    at Function.registerWith
    (http://localhost:60058/packages/cloud_firestore_web/src/write_batch_web.dart.lib.js:788:73)
    at Object.registerPlugins
    (http://localhost:60058/packages/chat/generated_plugin_registrant.dart.lib.js:30:46)
    at main (http://localhost:60058/web_entrypoint.dart.lib.js:44:35)
    at main.next (<anonymous>)
    at runBody (http://localhost:60058/dart_sdk.js:39051:34)
    at Object._async [as async] (http://localhost:60058/dart_sdk.js:39082:7)
    at main$ (http://localhost:60058/web_entrypoint.dart.lib.js:43:18)
    at http://localhost:60058/main_module.bootstrap.js:19:10
    at Array.forEach (<anonymous>)
    at window.$dartRunMain (http://localhost:60058/main_module.bootstrap.js:18:32)
    at <anonymous>:1:8
    at Object.runMain (http://localhost:60058/dwds/src/injected/client.js:8656:21)
    at http://localhost:60058/dwds/src/injected/client.js:22068:19
    at _wrapJsFunctionForAsync_closure.$protected
    (http://localhost:60058/dwds/src/injected/client.js:3830:15)
    at _wrapJsFunctionForAsync_closure.call$2 (http://localhost:60058/dwds/src/injected/client.js:10905:12) 
    at Object._asyncStartSync (http://localhost:60058/dwds/src/injected/client.js:3794:20)
    at main__closure1.$call$body$main__closure (http://localhost:60058/dwds/src/injected/client.js:22080:16)    at main__closure1.call$1 (http://localhost:60058/dwds/src/injected/client.js:22007:19)
    at StaticClosure._rootRunUnary [as call$2$5]
    (http://localhost:60058/dwds/src/injected/client.js:4153:16)
    at _CustomZone.runUnary$2$2 (http://localhost:60058/dwds/src/injected/client.js:12136:39)
    at _CustomZone.runUnaryGuarded$1$2 (http://localhost:60058/dwds/src/injected/client.js:12068:14)        
    at _ControllerSubscription._sendData$1 (http://localhost:60058/dwds/src/injected/client.js:11697:19)    
    at _DelayedData.perform$1 (http://localhost:60058/dwds/src/injected/client.js:11849:59)
    at _PendingEvents_schedule_closure.call$0 (http://localhost:60058/dwds/src/injected/client.js:11898:14) 
    at Object._microtaskLoop (http://localhost:60058/dwds/src/injected/client.js:3990:24)
    at StaticClosure._startMicrotaskLoop (http://localhost:60058/dwds/src/injected/client.js:3996:11)       
    at _AsyncRun__initializeScheduleImmediate_internalCallback.call$1
    (http://localhost:60058/dwds/src/injected/client.js:10774:9)
    at invokeClosure (http://localhost:60058/dwds/src/injected/client.js:1250:26)
    at MutationObserver.<anonymous> (http://localhost:60058/dwds/src/injected/client.js:1269:18)

我的整個 index.html 文件(我用“X”模糊了一些字段,因為我不確定它們是否是個人詳細信息):

<!DOCTYPE html>
<html>
<head>
  <!--
    If you are serving your web app in a path other than the root, change the
    href value below to reflect the base path you are serving from.
    The path provided below has to start and end with a slash "/" in order for
    it to work correctly.
    Fore more details:
    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
  -->
  <base href="/">

  <meta charset="UTF-8">
  <meta content="IE=Edge" http-equiv="X-UA-Compatible">
  <meta name="description" content="A new Flutter project.">

  <!-- iOS meta tags & icons -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-title" content="chat">
  <link rel="apple-touch-icon" href="icons/Icon-192.png">

  <!-- Favicon -->
  <link rel="icon" type="image/png" href="favicon.png"/>

  <title>chat</title>
  <link rel="manifest" href="manifest.json">
</head>
<body>
  <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->

  <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
  <script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-app.js"></script>

  <!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
  <script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-analytics.js"></script>

  <!-- Add Firebase products that you want to use -->
  <script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-auth.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-firestore.js"></script>
  <!-- This script installs service_worker.js to provide PWA functionality to
       application. For more information, see:
       https://developers.google.com/web/fundamentals/primers/service-workers -->
       <script>
        // TODO: Replace the following with your app's Firebase project configuration
        // For Firebase JavaScript SDK v7.20.0 and later, `measurementId` is an optional field
        var firebaseConfig = {
          // ...
        };
        const firebaseConfig = {
    apiKey: "XX",
    authDomain: "X",
    projectId: "chat-6052e",
    storageBucket: "XXXXX",
    messagingSenderId: "XXX",
    appId: "XX"
  };
        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);
      </script>
  <script>
    if ('serviceWorker' in navigator) {
      window.addEventListener('flutter-first-frame', function () {
        navigator.serviceWorker.register('flutter_service_worker.js');
      });
    }
  </script>
  
  <script src="main.dart.js" type="application/javascript"></script>
</body>
</html>

我的 main.dart function (它的開頭顯示我已經初始化 Firebase 就像許多其他答案一樣,這是解決方案):

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

我的 pubspec.yaml (其中一些顯示依賴項):

dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  google_fonts: ^2.0.0
  firebase_core: ^1.1.0
  firebase_auth: ^1.1.2
  google_sign_in: ^5.0.2
  email_validator: '^1.0.6'
  provider: ^5.0.0
  cloud_firestore: ^1.0.7

dev_dependencies:
  flutter_test:
    sdk: flutter

構建 gradle(整個東西):

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

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

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
}

應用程序級構建 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.google.gms.google-services'
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 30

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

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.chat"
        minSdkVersion 21 // was 16
        targetSdkVersion 30
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    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 {
    implementation platform('com.google.firebase:firebase-bom:27.1.0')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}

解決方案

因此,經過幾個小時的混亂,我確定我的 index.html 文件是問題所在。 將其更改為此解決了問題(我用 X 刪除了一些我認為可能敏感的字段?):

<!DOCTYPE html>
<html>
<head>
  <!--
    If you are serving your web app in a path other than the root, change the
    href value below to reflect the base path you are serving from.
    The path provided below has to start and end with a slash "/" in order for
    it to work correctly.
    Fore more details:
    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
  -->
  <base href="/">

  <meta charset="UTF-8">
  <meta content="IE=Edge" http-equiv="X-UA-Compatible">
  <meta name="description" content="A new Flutter project.">

  <!-- iOS meta tags & icons -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-title" content="chat">
  <link rel="apple-touch-icon" href="icons/Icon-192.png">

  <!-- Favicon -->
  <link rel="icon" type="image/png" href="favicon.png"/>

  <title>chat</title>
  <link rel="manifest" href="manifest.json">
</head>
<body>
  <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->

  <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
  <script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-app.js"></script>

  <!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
  <script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-analytics.js"></script>

  <!-- Add Firebase products that you want to use -->
  <script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-auth.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-firestore.js"></script>
  <!-- This script installs service_worker.js to provide PWA functionality to
       application. For more information, see:
       https://developers.google.com/web/fundamentals/primers/service-workers -->
       <script>
        // TODO: Replace the following with your app's Firebase project configuration
        // For Firebase JavaScript SDK v7.20.0 and later, `measurementId` is an optional field
        var firebaseConfig = {
          apiKey: "XXX",
    authDomain: "XXX",
    projectId: "XXX",
    storageBucket: "XXX",
    messagingSenderId: "XXX",
    appId: "XXX"
        };
        
        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);
      </script>
  <script>
    if ('serviceWorker' in navigator) {
      window.addEventListener('flutter-first-frame', function () {
        navigator.serviceWorker.register('flutter_service_worker.js');
      });
    }
  </script>
  
  <script src="main.dart.js" type="application/javascript"></script>
</body>
</html>

特定的錯誤消息來自未初始化 Firebase。 馬修的答案是正確的方法。 官方 Firesbase 文檔中存在一個空白,其中提供了 Firebase 配置 object 以及您的密鑰以插入 index.html。 如果你單獨復制這個,你仍然需要在下面立即添加以下行:

//初始化Firebase

    firebase.initializeApp(firebaseConfig);

您可以像下面這樣初始化默認應用程序;

Future<void> initializeDefault() async {
    FirebaseApp app = await Firebase.initializeApp();
    assert(app != null);
    setState(() {
      loading = false;
    }
    );
    print('Initialized default app $app');
  }

  @override
  void initState() {
    initializeDefault();
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(statusBarColor: Colors.transparent));
    super.initState();
  }

不要在代碼中使用兩個 Firebase.initializeApp() 語句。

為防止出現此錯誤,“未找到 com.google.android.gms.providerinstaller.dynamite 的本地模塊描述符 class”。

我遇到了同樣的問題。 異常很明顯:FirebaseApp 未初始化。 大多數答案建議在 main.dart 或index.html中初始化應用程序,但沒有一個對我有用:

// did not work for me, initilizeApp fails for flutter web
Future<void> main() async {
    try {
      await Firebase.initializeApp(name: fireStoreInstanceName);
    } on Exception catch (e) {
      print(e);
    }
    runApp(const MyApp());
}

/// index.html
/// did not work either, FireApp initilized in index.html is not accessible in dart
<script type="module">
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
    const firebaseConfig = {
      apiKey: "xxxxx",
      authDomain: "xxxxx",
      projectId: "noplans",
      storageBucket: "xxxx",
      messagingSenderId: "xxxx",
      appId: "1:xxxxx",
      measurementId: "xxxxx"
    };
    const app = initializeApp(firebaseConfig, "noplans");
    console.log("qqqqq 2, app = " + app.name);
  </script>

對我有用的是:

  1. 刪除 index.html 中的 init 語句
  2. main.dar中,如果是 web 應用程序,則使用選項初始化 FireApp
  3. 使用FirebaseFirestore.instanceFor而不是FirebaseFirestore.instance手動獲取 FirestoreInstance :
/// in main.dart
import 'package:flutter/foundation.dart' show kIsWeb;
...
if (kIsWeb) {
    await Firebase.initializeApp(
      name: fireStoreInstanceName,
      options: const FirebaseOptions(
          apiKey: "xxxxxxxxxxxx",
          appId: "1:xxxxxx",
          messagingSenderId: "xxxxxxx",
          projectId: "xxxx"),
    );
  } else {
    await Firebase.initializeApp(name: fireStoreInstanceName);
  }

/// to get Firestore instance
FirebaseFirestore? getFirestoreInstance() {
    for (var app in Firebase.apps) {
      if (app.name == fireStoreInstanceName) {
        return FirebaseFirestore.instanceFor(app: app);
      }
    }
    return null;
  }

    /// use of instance
    FirebaseFirestore? instance = getFirestoreInstance();
    if (instance == null) {
      return likes;
    }
    QuerySnapshot<Map<String, dynamic>> snapshot =
        await instance.collection("my_doc").get();

2022 年 9 月更新

我剛剛遇到這個錯誤我通過執行解決了它

flutter clean

並使用options參數但沒有name參數調用await Firebase.initializeApp()

苦苦掙扎后,我就這樣做了。

在 main.dart 添加以下代碼。 請注意這里,不要將name字段傳遞給 initializeApp。

if(kIsWeb || Platform.isAndroid){
  await Firebase.initializeApp(options: const FirebaseOptions(
    apiKey: "xxx",
    appId: "xxx",
    databaseURL: "xxx",
    messagingSenderId: "xxx",
    projectId: "xxx",
    storageBucket: "xxx",
  ));
}

而 index.html 應該如下所示。

<script type="module">
  // Import the functions you need from the SDKs you need
  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.10.0/firebase-app.js";
  // TODO: Add SDKs for Firebase products that you want to use
  // https://firebase.google.com/docs/web/setup#available-libraries

  // Your web app's Firebase configuration
  const firebaseConfig = {
    apiKey: "xxx",
    authDomain: "xxx",
    databaseURL: "xxx",
    projectId: "xxx",
    storageBucket: "xxx",
    messagingSenderId: "xxx",
    appId: "xxx"
  };

  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM