【问题标题】:Firebase doesn't work on flutter web but fine on android emulatorFirebase 在 Flutter Web 上无法运行,但在 android 模拟器上运行良好
【发布时间】:2021-09-24 05:46:31
【问题描述】:

我尝试在应用程序上使用 firebase auth,它在 android emu 上运行良好,并且能够创建帐户和登录,但不能在 web(chrome) 上。当我运行调试时,它给出了TypeError: Cannot read properties of undefined (reading 'app') 的错误。但是如果我运行flutter build web --release 并打开它返回的网络链接 ReferenceError: firebase is not defined。我已经google了好几天了,仍然无法解决这个问题。我处于死胡同,不知道该怎么办。 index.html 中的 const firebaseConfig = {...}; 在创建 webapp 项目时由 firebase auth 提供。 请帮忙。不知道哪里出错了。

flutter doctor
[√] Flutter (Channel stable, 2.5.0, on Microsoft Windows [Version 10.0.22454.1000],locale   
    en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
[√] Chrome - develop for the web
[√] Android Studio (version 2020.3)
[√] VS Code (version 1.60.2)
[√] Connected device (2 available)

flutter --version
Flutter 2.5.0 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 4cc385b4b8 (2 weeks ago) • 2021-09-07 23:01:49 -0700
Engine • revision f0826da7ef
Tools • Dart 2.14.0

在 pupspec.yaml 中

name: login_test
description: A new Flutter project.

publish_to: 'none'

version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  cupertino_icons: ^1.0.2
  firebase_auth: ^3.1.1
  firebase_core: ^1.6.0
  flutter:
    sdk: flutter
  fluttertoast: ^8.0.8
  form_field_validator: ^1.1.0

dev_dependencies:
  flutter_lints: ^1.0.0
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true

在 web/index.html 中

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

  <title>login_test</title>
  <link rel="manifest" href="manifest.json">
</head>
<body>
  <!-- Firebase Configuration -->
  <script type="module">
    // Import the functions you need from the SDKs you need
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js";
    // TODO: Add SDKs for Firebase products that you want to use
    // https://firebase.google.com/docs/web/setup#available-libraries
    import { auth } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-auth.js"
  
    // Your web app's Firebase configuration
    const firebaseConfig = {
      apiKey: "_________-_________",
      authDomain: "_________-_________.firebaseapp.com",
      projectId: "_________-_________",
      storageBucket: "_________-_________.appspot.com",
      messagingSenderId: "_________",
      appId: "1:_________:web:_________"
    };
  
    // Initialize Firebase
    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>
  <script src="main.dart.js" type="application/javascript"></script>
</body>
</html>

【问题讨论】:

    标签: firebase flutter firebase-authentication


    【解决方案1】:

    您应该真正遵循官方文档。如果您从一开始就仔细遵循它,它将带您到那里。您偶尔会看到类似这样的特定于网络的内容:

    https://firebase.flutter.dev/docs/installation/web https://firebase.flutter.dev/docs/firestore/overview#3-web-only-add-the-sdk

    我们可以按照这些说明在 Flutter Web 中使用它。您的 index.html 看起来与文档中的内容不同。您可能在某个地方学习了一个现在可能已经过时的教程。

    【讨论】:

    • 没有。我按照 firebase 控制台的说明操作,它告诉我从 link 添加 &lt;script type="module"&gt;........const app = initializeApp(firebaseConfig);&lt;/script&gt; 行和 import { auth } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-auth.js",因为在
    • 来自 firebase 控制台 link 的示例,它说 9.0.2 而不是来自 firebase.flutter.dev 的 8.6.1。所以我也很困惑该使用哪一个
    • 是的,你最好遵循 Flutter Firebase 文档而不是其他任何东西。甚至没有官方的 Firebase 网络文档,因为 Firebase 网络是另一种野兽。
    • 好的。谢谢。我已通过从 9.0.2 降级到 8.6.1 来修复它,并使用您给我的指令,而不使用 Firebase 控制台提供的 Firebase 配置脚本。
    【解决方案2】:

    我想我知道发生了什么。问题是将编译到 web 的 Flutter 与 Firebase web api 集成。 FlutterFire(它是与 Firebase 集成的 Flutter 库)是为了与 Firebase Web api 版本 8.6.1 集成而开发的。 另一方面,Firebase web api 已经在 9.x 版本中,它在初始化时有不同的方法调用。因此,解决方案是使用 Flutter web api 8.6.1 而不是像 de Flutter web api documentation 这样的 9.x。

    当初学者在控制台创建一个新的 Firebase 应用程序并且页面提供了一个代码来放置 Flutter Web index.html,但在这种情况下代码使用 Firebase Web api 9.x 版本样式时,会产生混淆。

    TL;DR;

    Flutter web/index.html 中的代码需要完全像这样。放入 body 标签的开头。只需替换您的 firebaseConfig 对象即可。

    <script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
    <script>
        var firebaseConfig = {
          apiKey: "----",
          authDomain: "----",
          projectId: "----",
          storageBucket: "----",
          messagingSenderId: "----",
          appId: "----"
        };
        firebase.initializeApp(firebaseConfig);
    </script>
    

    使用this libraries,但将版本替换为 8.6.1。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-27
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      • 1970-01-01
      相关资源
      最近更新 更多