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

10

15

I understand there are many very similar questions to this; but none of their solutions work for me. I've tried them all. PS: I expect the problem is something to do with my index.html

Problem: I am using Firebase (on Flutter web) and I am trying to authenticate users through it. However, my site won't even launch (blank screen) after I tried adding Firebase to it to get it to work. I'd appreciate some help figuring this out!

The Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app)

Notes: The problem occurs on Flutter web but works on my Android phone. Also, I have spent hours looking up every answer to all similar questions and none of their solutions work. Additionally, this is my first time asking a question, so please let me know if I'm doing anything wrong. Thanks!

Output for Error:

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)

My entire index.html file (some fields I've blurred with "X"s because I'm not sure if they're personal details):

<!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>

My main.dart function (the start of it showing I have initalized Firebase like many of the other answers say is the solution):

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

My pubspec.yaml (some of it showing dependencies):

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

Build gradle (entire thing):

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
}

App-level build gradle (entire thing):

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"
}
Fleuron answered 3/5, 2021 at 11:38 Comment(0)
F
25

copy/paste solution :)

So after a few more hours of messing around, I determined that my index.html file was the problem.

Copy the file below and replace your index.html with it, but change the fields with XXX's (they're unique to you I believe):

<!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>
Fleuron answered 4/5, 2021 at 19:14 Comment(5)
bless you :) i just spent 2 hours on this...Uncomfortable
I have wasted a day on this, I think this answer is the only article on the entire internet that solves the issue.Diffuser
I was reusing the project which I did 1 week ago, at that time everything was working fine. But in the new projects, I was getting errors. After wasting 2hr I replaced the Index file. Now It's working fine Thank you.Stain
Thank you! Not sure how you figured this one out :PReadymix
Didn't worked for mePtyalism
H
6

UPDATE Sep 2022

I just faced this error I solved it by executing

flutter clean

And call await Firebase.initializeApp() with options parameter but without name parameter

Helvetii answered 2/9, 2022 at 21:51 Comment(2)
YES!. call await Firebase.initializeApp() with options parameter but WITHOUT name parameter!. Somehow if name parameter is included firebase.initializedApp() will return ERROR [core/...]Gregor
YES, and doing this you don't need to use .js stuff.Ciprian
E
4

The particular error message comes from not initializing Firebase. Matthew's answer is the correct way. There is a gap in the official Firebase documentation where you are offered the Firebase configuration object with your keys to insert into index.html. If you copy this alone you will still need to add the following lines immediately under this:

    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
Englishman answered 27/9, 2021 at 8:49 Comment(0)
C
3

I ran into the same issue. The exception is prettry clear: the FirebaseApp is not initilized. Most of the answers recommended either initilized the app in main.dart or in index.html, but NONE of them worked for me:

// 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>

What have worked for me are:

  1. delete the init statements in the index.html
  2. in main.dar, init the FireApp with options if it is web application
  3. getting the FirestoreInstance manually with FirebaseFirestore.instanceFor instead of FirebaseFirestore.instance:
/// 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();

Convex answered 15/11, 2021 at 4:23 Comment(0)
N
1

As of now 10/2023 you don't need any JS or modifications to index.html at all for Flutter web. You just need to make sure the FirebaseOptions object in Dart has the appropriate values when initializing for the web.

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

  await Firebase.initializeApp(options: fbOptions);
} else {
  await Firebase.initializeApp();
}
Natatory answered 14/10, 2023 at 1:49 Comment(1)
Tried this but it doesnt work. Can you link the source of information? I could not find an updated guide to use firebase messsaging with flutter web.Fieldwork
M
1

I just had this problem happen in flutter web. It ran ok in debugging and in mobile but failed when deployed to the hosting site. After a few hours, here is how I solved the problem.

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

Apparently the tree-shake-icons method has a bug when building for web. Hope this helps.

Methenamine answered 19/10, 2023 at 19:20 Comment(0)
W
0

You can initialize default app like below;

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();
  }
Wonderland answered 3/5, 2021 at 14:43 Comment(2)
Unfortunately, this doesn't work. I placed your code in my first stateful widget (welcome screen of my project) and it produces the same error. Any other ideas?Fleuron
cloud_firestore: ^0.16.0 firebase_storage: ^7.0.0 firebase_core: ^0.7.0 They are old but I am still using these dependenciesWonderland
Z
0

Dont use two Firebase.initializeApp() statements in your code.

To prevent the this error, 'Local module descriptor class for com.google.android.gms.providerinstaller.dynamite not found'.

Zoezoeller answered 27/10, 2021 at 22:37 Comment(0)
G
0

After struggling a lot, I did it this way.

In main.dart add the below code. Please note here, do not pass the name field into the initializeApp.

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

While, the index.html should look like below.

<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>
Glissando answered 20/9, 2022 at 16:47 Comment(0)
K
0

In my code, I have to initialize Firebase in two ways.

For Web Build

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

For Mobile Build

await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform, name: "prod");
Kulda answered 28/4, 2023 at 6:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.