1
/// ESTE ES EL CODIGO///
import 'package:flutter/material.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 MaterialApp(
      title: 'Material App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Material App Bar'),
        ),
        body: Center(
          child: Container(
            child: Text('Hello World'),
          ),
        ),
      ),
    );
  }
}

/// ESTE ES EL ERROR ///

Performing hot restart...
Waiting for connection from debug service on Chrome...
Restarted application in 1.590ms.
Error: Assertion failed: file:///C:/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.5.3/lib/src/firebase_core_web.dart:273:11
options != null
"FirebaseOptions cannot be null when creating the default app."
at Object.throw_ [as throw] (http://localhost:59737/dart_sdk.js:5067:11)
at Object.assertFailed (http://localhost:59737/dart_sdk.js:4992:15)
at firebase_core_web.FirebaseCoreWeb.new.initializeApp (http://localhost:59737/packages/firebase_core_web/firebase_core_web.dart.lib.js:252:42)
at initializeApp.next ()
at http://localhost:59737/dart_sdk.js:40568:33
at _RootZone.runUnary (http://localhost:59737/dart_sdk.js:40438:59)
at _FutureListener.thenAwait.handleValue (http://localhost:59737/dart_sdk.js:35360:29)
at handleValueCallback (http://localhost:59737/dart_sdk.js:35928:49)
at Function._propagateToListeners (http://localhost:59737/dart_sdk.js:35966:17)
at _Future.new.[_completeWithValue] (http://localhost:59737/dart_sdk.js:35814:23) at async._AsyncCallbackEntry.new.callback (http://localhost:59737/dart_sdk.js:35835:35) at Object._microtaskLoop (http://localhost:59737/dart_sdk.js:40705:13) at _startMicrotaskLoop (http://localhost:59737/dart_sdk.js:40711:13) at http://localhost:59737/dart_sdk.js:36188:9


Este es mi Index.html
realicé el cambio pero sigue dando un error.

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

    For more details:
    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base

    This is a placeholder for base href that will be replaced by the value of
    the `--base-href` argument provided to `flutter build`.
  -->
  <base href="$FLUTTER_BASE_HREF">

  <meta charset="UTF-8">
  <meta content="IE=Edge" http-equiv="X-UA-Compatible">
  <meta name="description" content="Red Social">

  <!-- 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="faw">
  <link rel="apple-touch-icon" href="icons/Icon-192.png">

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

  <title>faw</title>
  <link rel="manifest" href="manifest.json">
</head>
<body>
<script defer src="/__/firebase/9.6.1/firebase-app-compat.js"></script>
<!-- include only the Firebase features as you need -->
<script defer src="/__/firebase/9.6.1/firebase-auth-compat.js"></script>
<script defer src="/__/firebase/9.6.1/firebase-database-compat.js"></script>
<script defer src="/__/firebase/9.6.1/firebase-firestore-compat.js"></script>
<script defer src="/__/firebase/9.6.1/firebase-functions-compat.js"></script>
<script defer src="/__/firebase/9.6.1/firebase-messaging-compat.js"></script>
<script defer src="/__/firebase/9.6.1/firebase-storage-compat.js"></script>
<script defer src="/__/firebase/9.6.1/firebase-analytics-compat.js"></script>
<script defer src="/__/firebase/9.6.1/firebase-remote-config-compat.js"></script>
<script defer src="/__/firebase/9.6.1/firebase-performance-compat.js"></script>
<!--
  initialize the SDK after all desired features are loaded, set useEmulator to false
  to avoid connecting the SDK to running emulators.
-->
<script src="https://www.gstatic.com/firebasejs/7.20.0/firebase-app.js"></script>
<!-- Firebase Auth SDK -->
<script src="https://www.gstatic.com/firebasejs/7.20.0/firebase-auth.js"></script>
<script defer src="/__/firebase/init.js?useEmulator=true"></script>
<script type="module">
  // Import the functions you need from the SDKs you need
  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.1/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: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: ""
  };

  // Initialize Firebase
   firebase.initializeApp(firebaseConfig)
  const app = initializeApp(firebaseConfig);
</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>
</html>

2
  • 1
    Si seleccionaste un dispositivo? parece que lo estas ejecutando en chrome Commented el 28 dic. 2021 a las 21:45
  • si, lo estoy ejecutando en chrome es una applicacion para web Commented el 29 dic. 2021 a las 17:26

2 respuestas 2

2

Ya no tienes que poner las opciones de configuración en index.html. Edite su main.dart así y sus errores deberían desaparecer.

await Firebase.initializeApp(
        options: FirebaseOptions(
           apiKey: "",
           authDomain: "",
           projectId: "",
           storageBucket: "",
           messagingSenderId: "1",
           appId: ""));
3
  • hice esa configuracion y ahora me da este error NoSuchMethodError: tried to call a non-function, such as null: 'dart.global.firebase.firestore' Commented el 1 ene. 2022 a las 21:10
  • 1
    Intente poner su javascript dentro de la <head></head> en lugar del <body></body> de su index.html
    – Scott
    Commented el 1 ene. 2022 a las 21:21
  • 1
    Además, solo llame a Firebase.initilizeApp una vez. Ya sea en index.html o main.dart
    – Scott
    Commented el 1 ene. 2022 a las 22:21
2

si estás tratando de correr en chrome tienes que poner esto en el index.html de la carpeta web antes del primer script que está ahí

<!-- The core Firebase JS SDK (always required for using any Firebase service) -->
    <script src="https://www.gstatic.com/firebasejs/7.20.0/firebase-app.js"></script>
    <!-- Firebase Auth SDK -->
    <script src="https://www.gstatic.com/firebasejs/7.20.0/firebase-auth.js"></script>
    <script>
      // Your web app's Firebase configuration
      var firebaseConfig = {
        apiKey: '...',
        authDomain: '...',
        databaseURL: '...',
        projectId: '...',
        storageBucket: '...',
        messagingSenderId: '...',
        appId: '...',
      }
      // Initialize Firebase
      firebase.initializeApp(firebaseConfig)
    </script>
    <!-- END OF FIREBASE INIT CODE -->

colocas los datos necesarios que ahí te pide los cuales firebase te da y debería funcionar.

1
  • hice esta configuracion y ahora me da este error NoSuchMethodError: tried to call a non-function, such as null: 'dart.global.firebase.firestore' Commented el 1 ene. 2022 a las 21:10

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.