Problem adding firebase to flutter web, TypeError: Cannot read properties of undefined (reading 'app')

384

In index.html use version 8.6.1 instead of this:

https://www.gstatic.com/firebasejs/9.0.1/firebase-storage.js

Use this for all the 9.0.1 libraries

Share:
384
Fadel
Author by

Fadel

Updated on January 01, 2023

Comments

  • Fadel
    Fadel over 1 year

    I'm trying to add firebase to a flutter project that will be used for android and web the integration with android was successful but I cant complete the web installation, I've read and tried all answers to problems similar to this on stackoverflow and everywhere else but nothing worked with me don't know what I'm missing.

    the packages added in my pubspec.yaml

      dependencies:
          ...
          firebase_core: ^1.6.0
          firebase_storage: ^10.0.3
          cloud_firestore: ^2.5.1
    

    Firebase app initialization in main.dart

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

    the index.html file

    <body>
      <script src="https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js"></script>
      <script src="https://www.gstatic.com/firebasejs/9.0.1/firebase-storage.js"></script>
      <script src="https://www.gstatic.com/firebasejs/9.0.1/firebase-firestore.js"></script>
      <script type="module">
        import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-analytics.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
        // For Firebase JS SDK v7.20.0 and later, measurementId is optional
        const firebaseConfig = {
          apiKey: "XXXXXXXXXXXXXXXXX",
          authDomain: "XXXXXXXXXXXXX",
          projectId: "XXXXXXXXXXXX",
          storageBucket: "XXXXXXXXXXXX",
          messagingSenderId: "XXXXXXXXXX",
          appId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
          measurementId: "XXXXXXXX"
        };
    
        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);
        const analytics = getAnalytics(app);
      </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>
        var serviceWorkerVersion = null;
        var scriptLoaded = false;
        function loadMainDartJs() {
          if (scriptLoaded) {
            return;
          }
          scriptLoaded = true;
          var scriptTag = document.createElement('script');
          scriptTag.src = 'main.dart.js';
          scriptTag.type = 'application/javascript';
          document.body.append(scriptTag);
        }
    
        if ('serviceWorker' in navigator) {
          // Service workers are supported. Use them.
          window.addEventListener('load', function () {
            // Wait for registration to finish before dropping the <script> tag.
            // Otherwise, the browser will load the script multiple times,
            // potentially different versions.
            var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
            navigator.serviceWorker.register(serviceWorkerUrl)
              .then((reg) => {
                function waitForActivation(serviceWorker) {
                  serviceWorker.addEventListener('statechange', () => {
                    if (serviceWorker.state == 'activated') {
                      console.log('Installed new service worker.');
                      loadMainDartJs();
                    }
                  });
                }
                if (!reg.active && (reg.installing || reg.waiting)) {
                  // No active web worker and we have installed or are installing
                  // one for the first time. Simply wait for it to activate.
                  waitForActivation(reg.installing ?? reg.waiting);
                } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
                  // When the app updates the serviceWorkerVersion changes, so we
                  // need to ask the service worker to update.
                  console.log('New service worker available.');
                  reg.update();
                  waitForActivation(reg.installing);
                } else {
                  // Existing service worker is still good.
                  console.log('Loading app from service worker.');
                  loadMainDartJs();
                }
              });
    
            // If service worker doesn't succeed in a reasonable amount of time,
            // fallback to plaint <script> tag.
            setTimeout(() => {
              if (!scriptLoaded) {
                console.warn(
                  'Failed to load app from service worker. Falling back to plain <script> tag.',
                );
                loadMainDartJs();
              }
            }, 4000);
          });
        } else {
          // Service workers not supported. Just drop the <script> tag.
          loadMainDartJs();
        }
      </script>
    </body>
    

    When I start debugging I get this Exception in web_entrypoint.dart file

    TypeError: Cannot read properties of undefined (reading 'app')
        at Object.app$ [as app] (http://localhost:59554/packages/firebase_core_web/src/interop/core.dart.lib.js:31:101)
        at new cloud_firestore_web.FirebaseFirestoreWeb.new (http://localhost:59554/packages/cloud_firestore_web/src/write_batch_web.dart.lib.js:819:64)
        at Function.registerWith (http://localhost:59554/packages/cloud_firestore_web/src/write_batch_web.dart.lib.js:731:73)
        at Object.registerPlugins (http://localhost:59554/packages/PROJECT_NAME/generated_plugin_registrant.dart.lib.js:20:46)
        at main (http://localhost:59554/web_entrypoint.dart.lib.js:31:35)
        at main.next (<anonymous>)
        at runBody (http://localhost:59554/dart_sdk.js:37422:34)
        at Object._async [as async] (http://localhost:59554/dart_sdk.js:37453:7)
        at main$ (http://localhost:59554/web_entrypoint.dart.lib.js:30:18)
        at http://localhost:59554/main_module.bootstrap.js:19:10
        at Array.forEach (<anonymous>)
        at window.$dartRunMain (http://localhost:59554/main_module.bootstrap.js:18:32)
        at <anonymous>:1:8
        at Object.runMain (http://localhost:59554/dwds/src/injected/client.js:8825:21)
        at http://localhost:59554/dwds/src/injected/client.js:22713:19
        at _wrapJsFunctionForAsync_closure.$protected (http://localhost:59554/dwds/src/injected/client.js:3851:15)
        at _wrapJsFunctionForAsync_closure.call$2 (http://localhost:59554/dwds/src/injected/client.js:11063:12)
    
  • rkunboxed
    rkunboxed about 2 years
    This worked for me but does anyone know why we can't use the latest?
  • Huthaifa Muayyad
    Huthaifa Muayyad about 2 years