开发者问题收集

Flutter web Firebase 初始化错误

2022-07-20
2749

当我启动 Flutter Web 应用时,出现此错误:

[core/not-initialized] Firebase has not been correctly initialized. Usually this means you've attempted to use a Firebase service before calling Firebase.initializeApp .

<!DOCTYPE html>
<html>
<head>
    ...
</head>
<body>
  <script type="module">
    // Import the functions you need from the SDKs you need
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.9.0/firebase-app.js";
    import { auth } from 'https://www.gstatic.com/firebasejs/9.9.0/firebase-auth.js'
    import { firestore } from 'https://www.gstatic.com/firebasejs/9.9.0/firebase-firestore.js'  
    // https://firebase.google.com/docs/web/setup#available-libraries
  
    // Your web app's Firebase configuration
    const firebaseConfig = {
      apiKey: "xxx",
      authDomain: "xxx",
      projectId: "xxx",
      storageBucket: "xxx",
      messagingSenderId: "xxx",
      appId: "xxx"
    };
  
    // 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>
         ...
  </script>
</body>
</html>

如您所见,firebase 在 index.html 文件中初始化。 我已经安装了所有需要的库,以下是列表:

  • firebase_auth:^3.4.2
  • cloud_firestore:^3.3.0
  • firebase_core:^1.19.2

我应该在 Flutter 中初始化 firebase 吗?

1个回答
 if (kIsWeb) 
    await Firebase.initializeApp(
      options: FirebaseOptions(
        apiKey: "xxx",
        appId: "xxx",
        messagingSenderId: "xxx",
        projectId: "xxx",
      ),
    );
else
   await Firebase.initializeApp();

将上述代码添加到您的 main.dart 文件中。 (kIsWeb 将检查应用程序是否正在 Web 上运行)

Pooja
2022-07-20