簡體   English   中英

Flutter Web 應用程序未設置 Firebase

[英]Flutter web app not setting up with firebase

自從我嘗試使用 Flutter Web 應用程序設置 Firebase 以來已經 3 周了。 我一直在互聯網上關注教程,但沒有一個能夠幫助我。 每次我得到同樣的錯誤。

這是我的 main.dart

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

這是我的 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="quiz_app_4">
  <link rel="apple-touch-icon" href="icons/Icon-192.png">

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

  <title>quiz_app_4</title>
  <link rel="manifest" href="manifest.json">
</head>
<body>
  <script type="module">
    // Import the functions you need from the SDKs you need
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.8/firebase-app.js";
    import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.8/firebase-analytics.js";
    // TODO: Add SDKs for Firebase products that you want to use
    // https://firebase.google.com/docs/web/setup#available-libraries
    import { } from 'firebase/auth';
    import { } from 'firebase/database';
  
    // Your web app's Firebase configuration
    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
    const firebaseConfig = {
      apiKey: "...",
      authDomain: "...",
      projectId: "...",
      storageBucket: "...",
      messagingSenderId: "...",
      appId: "...",
      measurementId: "..."
    };
  
    // 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) {
      window.addEventListener('load', function () {
        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();
            }
          });

        setTimeout(() => {
          if (!scriptLoaded) {
            console.warn(
              'Failed to load app from service worker. Falling back to plain <script> tag.',
            );
            loadMainDartJs();
          }
        }, 4000);
      });
    } else {
      loadMainDartJs();
    }
  </script>


</body>
</html>

這些是我的 pubspec.yaml 依賴項。

...
dependencies:
  flutter:
    sdk: flutter


  cupertino_icons: ^1.0.2

  firebase_core: ^1.13.1
  firebase_database: ^9.0.8
  firebase_auth: ^3.3.9
  # firebase_core_web: ^1.6.1

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^1.0.0
...

這些是我得到的錯誤。

Launching lib\main.dart on Chrome in debug mode...
Error: Couldn't resolve the package 'http' in 'package:http/http.dart'. 
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/firebase_core_web.dart:10:8: Error: Not found:
'package:http/http.dart'
import 'package:http/http.dart' as http;
       ^
../../flutter/packages/flutter_web_plugins/lib/src/navigation/js_url_strategy.dart:48:14: Error: Method not found: 'allowInterop'.
    getPath: allowInterop(strategy.getPath),
             ^^^^^^^^^^^^
../../flutter/packages/flutter_web_plugins/lib/src/navigation/js_url_strategy.dart:49:15: Error: Method not found: 'allowInterop'.
    getState: allowInterop(strategy.getState),
              ^^^^^^^^^^^^
../../flutter/packages/flutter_web_plugins/lib/src/navigation/js_url_strategy.dart:50:26: Error: Method not found: 'allowInterop'.
    addPopStateListener: allowInterop(strategy.addPopStateListener),
                         ^^^^^^^^^^^^
../../flutter/packages/flutter_web_plugins/lib/src/navigation/js_url_strategy.dart:51:25: Error: Method not found: 'allowInterop'.
    prepareExternalUrl: allowInterop(strategy.prepareExternalUrl),
                        ^^^^^^^^^^^^
../../flutter/packages/flutter_web_plugins/lib/src/navigation/js_url_strategy.dart:52:16: Error: Method not found: 'allowInterop'.
    pushState: allowInterop(strategy.pushState),
               ^^^^^^^^^^^^
../../flutter/packages/flutter_web_plugins/lib/src/navigation/js_url_strategy.dart:53:19: Error: Method not found: 'allowInterop'.
    replaceState: allowInterop(strategy.replaceState),
                  ^^^^^^^^^^^^
../../flutter/packages/flutter_web_plugins/lib/src/navigation/js_url_strategy.dart:54:9: Error: Method not found: 'allowInterop'.
    go: allowInterop(strategy.go),
        ^^^^^^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/firebase_core_web.dart:48:15: Error: Method not found: 'getProperty'.  if (js_util.getProperty(e, 'name') == 'FirebaseError') {
              ^^^^^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/firebase_core_web.dart:49:20: Error: Method not found: 'getProperty'.    return js_util.getProperty(e, 'code') ?? '';
                   ^^^^^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/firebase_core_web.dart:61:15: Error: Method not found: 'getProperty'.  if (js_util.getProperty(e, 'name') == 'FirebaseError') {
              ^^^^^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/firebase_core_web.dart:62:30: Error: Method not found: 'getProperty'.    String rawCode = js_util.getProperty(e, 'code');
                             ^^^^^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/firebase_core_web.dart:64:30: Error: Method not found: 'getProperty'.    String message = js_util.getProperty(e, 'message') ?? '';
                             ^^^^^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/src/firebase_core_web.dart:36:12: Error: The getter 'context' isn't  
defined for the class 'FirebaseCoreWeb'.
 - 'FirebaseCoreWeb' is from 'package:firebase_core_web/firebase_core_web.dart'
 ('../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/firebase_core_web.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'context'.
    return context['require'] != null;
           ^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/src/firebase_core_web.dart:45:12: Error: The getter 'context' isn't  
defined for the class 'FirebaseCoreWeb'.
 - 'FirebaseCoreWeb' is from 'package:firebase_core_web/firebase_core_web.dart'
 ('../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/firebase_core_web.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'context'.
    return context['flutterfire_web_sdk_version'] ??
           ^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/src/firebase_core_web.dart:61:7: Error: 'JsObject' isn't a type.     
      JsObject ignored =
      ^^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/src/firebase_core_web.dart:62:11: Error: The getter 'JsObject' isn't 
defined for the class 'FirebaseCoreWeb'.
 - 'FirebaseCoreWeb' is from 'package:firebase_core_web/firebase_core_web.dart'
 ('../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/firebase_core_web.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'JsObject'.
          JsObject.fromBrowserObject(context['flutterfire_ignore_scripts']);
          ^^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/src/firebase_core_web.dart:62:38: Error: The getter 'context' isn't  
defined for the class 'FirebaseCoreWeb'.
 - 'FirebaseCoreWeb' is from 'package:firebase_core_web/firebase_core_web.dart'
 ('../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/firebase_core_web.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'context'.
          JsObject.fromBrowserObject(context['flutterfire_ignore_scripts']);
                                     ^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/src/firebase_core_web.dart:79:5: Error: 'ScriptElement' isn't a type.    ScriptElement script = ScriptElement();
    ^^^^^^^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/src/firebase_core_web.dart:79:28: Error: The method 'ScriptElement'  
isn't defined for the class 'FirebaseCoreWeb'.
 - 'FirebaseCoreWeb' is from 'package:firebase_core_web/firebase_core_web.dart'
 ('../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/firebase_core_web.dart').
Try correcting the name to the name of an existing method, or defining a method named 'ScriptElement'.
    ScriptElement script = ScriptElement();
                           ^^^^^^^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/src/firebase_core_web.dart:83:12: Error: The getter 'document' isn't 
defined for the class 'FirebaseCoreWeb'.
 - 'FirebaseCoreWeb' is from 'package:firebase_core_web/firebase_core_web.dart'
 ('../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/firebase_core_web.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'document'.
    assert(document.head != null);
           ^^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/src/firebase_core_web.dart:84:5: Error: The getter 'document' isn't  
defined for the class 'FirebaseCoreWeb'.
 - 'FirebaseCoreWeb' is from 'package:firebase_core_web/firebase_core_web.dart'
 ('../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/firebase_core_web.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'document'.
    document.head!.append(script);
    ^^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/src/firebase_core_web.dart:93:9: Error: The getter 'context' isn't
defined for the class 'FirebaseCoreWeb'.
 - 'FirebaseCoreWeb' is from 'package:firebase_core_web/firebase_core_web.dart'
 ('../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/firebase_core_web.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'context'.
    if (context['firebase'] != null) {
        ^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/src/firebase_core_web.dart:134:5: Error: 'JsObject' isn't a type.    
    JsObject require = JsObject.fromBrowserObject(context['require']);
    ^^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/src/firebase_core_web.dart:126:9: Error: The getter 'context' isn't  
defined for the class 'FirebaseCoreWeb'.
 - 'FirebaseCoreWeb' is from 'package:firebase_core_web/firebase_core_web.dart'
 ('../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/firebase_core_web.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'context'.
    if (context['firebase'] != null) {
        ^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/src/firebase_core_web.dart:134:24: Error: The getter 'JsObject' isn'tdefined for the class 'FirebaseCoreWeb'.
 - 'FirebaseCoreWeb' is from 'package:firebase_core_web/firebase_core_web.dart'
 ('../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/firebase_core_web.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'JsObject'.
    JsObject require = JsObject.fromBrowserObject(context['require']);
                       ^^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/src/firebase_core_web.dart:134:51: Error: The getter 'context' isn't 
defined for the class 'FirebaseCoreWeb'.
 - 'FirebaseCoreWeb' is from 'package:firebase_core_web/firebase_core_web.dart'
 ('../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/firebase_core_web.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'context'.
    JsObject require = JsObject.fromBrowserObject(context['require']);
                                                  ^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/src/firebase_core_web.dart:136:7: Error: The getter 'JsObject' isn't 
defined for the class 'FirebaseCoreWeb'.
 - 'FirebaseCoreWeb' is from 'package:firebase_core_web/firebase_core_web.dart'
 ('../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.6.1/lib/firebase_core_web.dart').
...


(package:frontend_server/src/javascript_bundle.dart:164:65)
    <asynchronous suspension>
    #2      FrontendCompiler.writeJavascriptBundle (package:frontend_server/frontend_server.dart:665:32)
    <asynchronous suspension>
    #3      FrontendCompiler.compile (package:frontend_server/frontend_server.dart:573:9)
    <asynchronous suspension>
    #4      listenAndCompile.<anonymous closure> (package:frontend_server/frontend_server.dart:1154:11)
    <asynchronous suspension>
    the Dart compiler exited unexpectedly.
    Waiting for connection from debug service on Chrome...             26.1s
    Failed to compile application.

將 http 添加到我的依賴項消除了

Error: Couldn't resolve the package 'http' in 'package:http/http.dart'. 

我的項目只需要 firebase 身份驗證和 firebase 實時數據庫。

我是 Flutter 的新手,並且已經構建了我的應用程序,它在 android 上運行良好,但我需要它作為一個 Web 應用程序來將它托管在服務器上。

如果有人幫助我,那真的會讓我的生活更輕松。 謝謝你。

你做了flutter clean嗎? 你的代碼看起來很簡單。 我發現的唯一一件事是,在您的Firebase.initializeApp中,您沒有提供從 Firebase 獲得的選項屬性:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
  // pass the options from the Firebase SDK configuration
  options: const FirebaseOptions(
      apiKey: "XXX",
      authDomain: "XXX",
      databaseURL: "XXX",
      projectId: "XXX",
      storageBucket: "XXX",
      messagingSenderId: "XXX",
      appId: "XXX"
    ));
  runApp(const MyApp());
}

在將Web平台添加到一個巨大的 2 年歷史的Flutter項目中,該項目大量使用Firebase (函數、分析等)時,這種設置對我很有用。

  • 我在“pubspec.yaml”中導入了我的庫
  • 我已經像所有顫振文檔推薦的那樣初始化了項目

劇情發生在 index.html 中。 在不同的文檔中,結合了新舊兩種做事方式:或者更確切地說,您將在一個簡單的 Web 項目中使用 Firebase Web 的方式,而不是在使用 Firebase 的 Flutter Web 項目中使用 Web 工作的方式。 經過幾天的搜索......原來我不打算使用最新的firebasejs。 (其中一個錯誤提示了我)。

基本上最新的 firebasejs/9.xx 破壞了一切,出現了奇怪的神秘錯誤,但突然轉移到 firebasejs/8.10.1 一切正常。

修正我的錯誤:

  • 把這些放在標簽里
  • 不要導入帶有 CDN 導入標簽的庫,例如<script src="https://www.gstatic.com/firebasejs...
  • <script type="module">標記中使用新的空括號 { } 導入庫,或者通過指定每個庫的哪些部分
  • 首先導入firebase-app.js
  • 不需要const firebaseConfig = {...}const app = firebase.initializeApp(firebaseConfig);

不需要這個:

// script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script>

// script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-functions.js"></script>

// script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-analytics.js"></script>

// script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-firestore.js"></script>

但這很重要:

import {  } from "https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js";

import {  } from "https://www.gstatic.com/firebasejs/8.10.1/firebase-firestore.js";

import {  } from "https://www.gstatic.com/firebasejs/8.10.1/firebase-functions.js";

import {  } from "https://www.gstatic.com/firebasejs/8.10.1/firebase-analytics.js";
</script>

<script>

不需要這個:

//const firebaseConfig = {...};

//const app = firebase.initializeApp(firebaseConfig);

//const db = getFirestore(app);

</script>

//then rest of the Body tag

重新安裝顫振解決了我的問題。

導航到您的 android-sdk、flutter 和項目所在的文件夾。

刪除顫振文件夾。

https://docs.flutter.dev/get-started/install下載顫振 zip

將其提取到您刪除之前的顫振文件夾的同一文件夾中。

你已准備好出發!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM