[英]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.自从我尝试使用 Flutter Web 应用程序设置 Firebase 以来已经 3 周了。 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这是我的 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这是我的 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.这些是我的 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
...
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将 http 添加到我的依赖项消除了
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.我的项目只需要 firebase 身份验证和 firebase 实时数据库。
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.我是 Flutter 的新手,并且已经构建了我的应用程序,它在 android 上运行良好,但我需要它作为一个 Web 应用程序来将它托管在服务器上。
It would really make my life alot easier if anyone helped me.如果有人帮助我,那真的会让我的生活更轻松。 Thank you.谢谢你。
Did you do a flutter clean ?你做了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:我发现的唯一一件事是,在您的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());
}
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).在将Web平台添加到一个巨大的 2 年历史的Flutter项目中,该项目大量使用Firebase (函数、分析等)时,这种设置对我很有用。
The drama happened in the index.html.剧情发生在 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.在不同的文档中,结合了新旧两种做事方式:或者更确切地说,您将在一个简单的 Web 项目中使用 Firebase Web 的方式,而不是在使用 Firebase 的 Flutter Web 项目中使用 Web 工作的方式。 Afted days of searching... Turned out that I was not meant to use the most recent firebasejs.经过几天的搜索......原来我不打算使用最新的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.基本上最新的 firebasejs/9.xx 破坏了一切,出现了奇怪的神秘错误,但突然转移到 firebasejs/8.10.1 一切正常。
Fixes to my mistakes:修正我的错误:
<script src="https://www.gstatic.com/firebasejs...
不要导入带有 CDN 导入标签的库,例如<script src="https://www.gstatic.com/firebasejs...
<script type="module">
tag with the new, empty bracket { }, ot by specifying which parts of each library在<script type="module">
标记中使用新的空括号 { } 导入库,或者通过指定每个库的哪些部分firebase-app.js
first首先导入firebase-app.js
const firebaseConfig = {...}
or for const app = firebase.initializeApp(firebaseConfig);
不需要const firebaseConfig = {...}
或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.导航到您的 android-sdk、flutter 和项目所在的文件夹。
Delete the flutter folder.删除颤振文件夹。
Download flutter zip from https://docs.flutter.dev/get-started/install从https://docs.flutter.dev/get-started/install下载颤振 zip
Extract it to the same folder from where you deleted your previous flutter folder.将其提取到您删除之前的颤振文件夹的同一文件夹中。
You are good to go!你已准备好出发!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.