Uncaught ReferenceError: firebase is not defined in Flutter

Issue

I am not able to initialize Firebase in my Flutter project I have tried importing the firebase-app.js ,firebase-auth.js and firebase-analytics.js but nothing worked I am currently using Firebase 9.0.1, I am tired of solving this error its not been solved from 1 week and I have tried everything on Stackoverflow and searched the documentation on Firebase and Flutter I have attached screenshot of the error check below which I get when build and run,

Also I have enabled firebase functions in my firebase console so does it needs to be imported to my project as of now I ain’t using it but is it mandatory to so?

First time when run flutter run -d chrome the Error Output is,

enter image description here

main.dart:

import 'package:flutter/material.dart';
import 'package:devcom/auth.dart';
import 'package:devcom/auth_provider.dart';
import 'package:devcom/root_page.dart';
import 'package:firebase_core/firebase_core.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return AuthProvider(
      auth: Auth(),
      child: MaterialApp(
        title: 'Flutter login demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: RootPage(),
      ),
    );
  }
}

index.html:

<!DOCTYPE html>
  <html>
  <head>
   
    <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="devcom">
    <link rel="apple-touch-icon" href="icons/Icon-192.png">
  
    <!-- Favicon -->
    <link rel="shortcut icon" type="image/png" href="favicon.png" />
  
    <title>Devcom</title>
    <link rel="manifest" href="manifest.json">
  </head>
<body > 
    <script src="https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js" type = "module"></script>
    <script src="https://www.gstatic.com/firebasejs/9.0.1/firebase-analytics.js" type="module"> </script>
    <script src="https://www.gstatic.com/firebasejs/9.0.1/firebase-auth.js" type = "module"></script>
    <script src="https://www.gstatic.com/firebasejs/9.0.1/firebase-firestore.js" type="module"></script>
  <!-- The core Firebase JS SDK is always required and must be listed first --><script> var firebaseConfig = {
      apiKey: "...",
      authDomain: "......",
      databaseURL: ".....",
      projectId: "...",
      storageBucket: "",
      messagingSenderId: "",
      measurementId: "",
      appId: "1:.........:web:...........",
    };
    firebase.initializeApp(firebaseConfig); // the error is pointing out this line for the cause 
    firebase.analytics();
</script><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>
</html>
 

pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter
  firebase_auth: 
  cupertino_icons: 
  firebase_core: 
  firebase_core_web:
  firebase_auth_web:
    
dev_dependencies:
  flutter_test:
    sdk: flutter
  mockito:

Edits suggested for using version 8.7.1:

it throws me : Failed to load resource: net::ERR_NAME_NOT_RESOLVED

Solution

The problem cause was Auth used in Myapp class in main.dart it works fine if we remove the AuthProvider widget from there and also the version needs to be changed from 9 to version 8.7.1 as Flutter bindings are built on that and the support for version 9 is yet to come.

Answered By – Abhishek Vishwakarma

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *