将firebase添加到flutter web时出现问题,TypeError:无法读取未定义的属性(读取“应用程序”)

Posted

技术标签:

【中文标题】将firebase添加到flutter web时出现问题,TypeError:无法读取未定义的属性(读取“应用程序”)【英文标题】:Problem adding firebase to flutter web, TypeError: Cannot read properties of undefined (reading 'app') 【发布时间】:2021-11-03 19:25:42 【问题描述】:

我正在尝试将 firebase 添加到将用于 android 和 web 的颤振项目中*** 和其他任何地方,但没有什么对我有用,不知道我错过了什么。

在我的pubspec.yaml中添加的包

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

main.dart

中的 Firebase 应用初始化
main() async 
  WidgetsFlutterBinding.ensureInitialized();
  Firebase.initializeApp();
  runApp(MyApp());

index.html 文件

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

当我开始调试时,我在 web_entrypoint.dart 文件中得到了这个异常

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)

【问题讨论】:

【参考方案1】:

在 index.html 中使用 8.6.1 版本而不是这个:

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

将此用于所有 9.0.1 库

【讨论】:

以上是关于将firebase添加到flutter web时出现问题,TypeError:无法读取未定义的属性(读取“应用程序”)的主要内容,如果未能解决你的问题,请参考以下文章

添加 firebase 后构建 Flutter apk 时出现 Gradle 错误

当我为flutter web添加firebase时,我的应用程序将无法运行

在android studio中将firebase添加到flutter时出错:插件项目:firebase_core_web未找到。请更新 settings.gradle [重复]

在 Flutter Web 中实现 Firebase 分析

如何将 Flutter 项目迁移到 Firebase 版本 9 现代 Web 模块化风格

Flutter web - 无法将图像上传到 Firebase 存储