본문 바로가기

개발하자

Flower Web - Firebase App '[DEFAULT]'가 생성되지 않음 - Firebase App.initializeApp()(앱/no-app)을 호출합니다

반응형

Flower Web - Firebase App '[DEFAULT]'가 생성되지 않음 - Firebase App.initializeApp()(앱/no-app)을 호출합니다

이와 유사한 질문들이 많다는 것을 알고 있지만, 그들의 어떤 해결책도 저에게 통하지 않습니다. 다 먹어봤어요. 추신: 문제는 제 index.html과 관련이 있을 것으로 예상됩니다

파이어베이스(Fluter web)를 사용하고 있으며 이를 통해 사용자 인증을 시도하고 있습니다. 하지만 내 사이트는 파이어베이스를 추가해 작동시키려 했지만(빈 화면) 실행조차 되지 않는다. 이것을 알아내는데 도움을 좀 주면 고맙겠어요!

Firebase App '[Default]'이(가) 생성되지 않았습니다. Firebase App.initializeApp()(app/no-app)을 호출합니다

문제는 플러터 웹에서 발생하지만 내 안드로이드 폰에서 작동한다. 또한, 저는 몇 시간 동안 모든 유사한 질문에 대한 모든 답변을 찾아봤지만, 그들의 해결책은 하나도 통하지 않았습니다. 추가로 제가 질문을 하는 건 처음이라 혹시 잘못하고 있는 부분이 있으면 말씀해주세요. 고마워요!

오류에 대한 출력:

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>

나의 메인.dart 기능(다른 많은 답변들이 해결책이라고 말하는 것처럼 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

그라들(전체) 제작:

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
}

앱 레벨 빌드 그라들(전체):

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"
}



나는 방금 플러터 웹에서 이 문제가 발생했다. 디버깅과 모바일에서는 괜찮았지만 호스팅 사이트에 배포했을 때 실패했다. 몇 시간 후, 제가 문제를 해결한 방법은 이렇습니다.

run: flutter build web --no-tree-shake-icons

트리쉐이크 아이콘 방식은 웹용으로 빌드할 때 버그가 있는 것입니다. 이게 도움이 됐으면 좋겠네요.




2023년 10월 10일 현재 Flutter 웹에 대해 Index.html에 대한 JS나 수정사항이 전혀 필요하지 않습니다. Dart의 FirebaseOptions 개체가 웹을 초기화할 때 적절한 값을 가지도록 하면 됩니다.

if (kIsWeb) {
  var fbOptions = FirebaseOptions(
      apiKey: 'xxxxxxxx',
      appId: '1:xxxxxxxxxxx',
      messagingSenderId: 'xxxxxxxxxxxx',
      projectId: 'xxxxxxxxxxxxx');

  await Firebase.initializeApp(options: fbOptions);
} else {
  await Firebase.initializeApp();
}



아래와 같이 기본 앱을 초기화할 수 있습니다;

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();
  }



해결책

그래서 몇 시간 더 빈둥거리다가 내 파일이 문제라는 결론을 내렸어요.

아래의 파일을 복사하여 파일로 바꾸되, 필드를 XXX로 변경합니다(당신에게 유일한 파일입니다):

<!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를 초기화하지 않는 것에서 발생합니다. 매튜의 대답이 정확한 방법입니다. 공식 Firebase 문서에 index.html에 삽입할 키가 있는 Firebase 구성 개체가 제공되는 공백이 있습니다. 이것만 복사해도 이 아래에 다음 행을 바로 추가해야 합니다:

    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);



파이어베이스 2개를 사용하지 마십시오.코드에서 App() 문을 초기화합니다.

이 오류를 방지하려면 'com.google.android.gms.providerinstaller.dynamite에 대한 로컬 모듈 설명자 클래스를 찾을 수 없습니다.'




저도 같은 문제에 부딪혔어요. 예외는 명확합니다. 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. 인덱스에서 init 문을 삭제합니다
  2. 에서 웹 애플리케이션인 경우 옵션을 사용하여 FireApp을 시작합니다
  3. 파이어스토어를 받기다음 대신 수동으로 인스턴스화:
/// 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

그리고 매개변수는 사용하지만 매개변수는 사용하지 않는 호출




고생을 많이 한 끝에 이런 식으로.

main.dart에 아래 코드를 추가한다. 필드를 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>



내 코드로는 파이어베이스를 두 가지 방법으로 초기화해야 한다.

웹 빌드용

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

모바일 빌드용

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

반응형