简体   繁体   中英

Flutter web app not setting up with firebase

It has been 3 weeks since I have been trying to set up firebase with a flutter web app. I have been following tutorials all over the internet but none of them have been able to help me. Every time I get the same errors.

This is my 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.
    );
  }
}

This is my 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>

These are my pubspec.yaml dependencies.

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

These are the errors I get.

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.

Adding http to my dependencies eliminates

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

I need only the firebase authentication and firebase realtime database for my project.

I am new to flutter and have already built my app and it works fine on android but I need it as a web app to host it on a server.

It would really make my life alot easier if anyone helped me. Thank you.

Did you do a flutter clean ? your code looks pretty straightforward. The only thing I spotted was that in your Firebase.initializeApp you are not providing the options properties you get from 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());
}

This setup has worked for me when adding Web platform to a gigantic 2-year-old Flutter project which heavily uses Firebase (functions, analytics, etc).

  • I had my libraries imported in 'pubspec.yaml'
  • I had initialised the project like all the flutter docs recommend

The drama happened in the index.html. In different docs there was a combination of new and old ways of doing things: or rather the way you would do firebase web in a simple Web project, vs. how you would make Web work in a Flutter Web project with Firebase. Afted days of searching... Turned out that I was not meant to use the most recent firebasejs. (one of the errors hinted me to it).

Basically the newest firebasejs/9.xx broke everything, with weird mysterious errors, but moving to firebasejs/8.10.1 suddently everything works.

Fixes to my mistakes:

  • put these in tag
  • Do NOT import libraries with CDN import tags like <script src="https://www.gstatic.com/firebasejs...
  • import libraries in a <script type="module"> tag with the new, empty bracket { }, ot by specifying which parts of each library
  • import firebase-app.js first
  • no need for const firebaseConfig = {...} or for const app = firebase.initializeApp(firebaseConfig);

No Need for This:

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

But this is important:

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>

And no Need for This:

//const firebaseConfig = {...};

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

//const db = getFirestore(app);

</script>

//then rest of the Body tag

Reinstalling flutter fixed my issue.

Navigate to the folder where your android-sdk, flutter, and projects reside.

Delete the flutter folder.

Download flutter zip from https://docs.flutter.dev/get-started/install

Extract it to the same folder from where you deleted your previous flutter folder.

You are good to go!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM