所以我遇到了这个错误,我一直试图用可用的资源(包括StackOverflow(来修复这个错误。什么都不起作用,我仍然得到同样的错误";没有创建Firebase应用程序[DEFAULT]=调用Firebase.initializeApp((">
这是我的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="cyber_education">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<title>cyber_education</title>
<link rel="manifest" href="manifest.json">
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-firestore.js"></script>
<script type="module">
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "xxxx",
authDomain: "xxxxx",
projectId: "xxxx",
storageBucket: "xxxxx",
messagingSenderId: "xxxxxx",
appId: "xxxxxxxx"
};
// 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) {
// 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>
</html>
此处的main.dart文件:
// ignore_for_file: prefer_const_constructors
//Imports
import 'register.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
//This line is very important
//Without it the app doesn't work
WidgetsFlutterBinding.ensureInitialized();
Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.dark(),
home: Login(),
);
}
}
class Login extends StatefulWidget {
const Login({Key? key}) : super(key: key);
@override
_LoginState createState() => _LoginState();
}
class _LoginState extends State<Login> {
FirebaseAuth _auth = FirebaseAuth.instance;
//Variables
String email = '';
String password = '';
//Controllers
TextEditingController emailController = TextEditingController();
TextEditingController passwordController = TextEditingController();
Future<void> loginUser() async {
await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email,
password: password,
);
/* Navigator.push(
context, MaterialPageRoute(builder: (context) => const HomePage()));*/
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Login'),
),
body: Column(
children: <Widget>[
Center(
child: Padding(
padding: EdgeInsets.only(
top: 30,
),
child: SizedBox(
width: 300,
child: TextField(
controller: emailController,
onChanged: (value) {
email = value;
},
decoration: InputDecoration(
hintText: 'Email',
),
),
),
),
),
Center(
child: Padding(
padding: EdgeInsets.only(
top: 30,
),
child: SizedBox(
width: 300,
child: TextField(
controller: passwordController,
//Get user input and store it in password variable
onChanged: (value) {
password = value;
},
decoration: InputDecoration(
hintText: 'Password',
),
),
),
),
),
Center(
child: Padding(
padding: EdgeInsets.only(
top: 20,
),
child: SizedBox(
width: 70,
height: 40,
child: ElevatedButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all<Color>(Colors.orange),
),
onPressed: () {
loginUser();
},
child: Text('Login'),
),
),
)),
Padding(
padding: EdgeInsets.only(
top: 20,
),
child: TextButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => Register()));
},
child: Text('Not a user? Register!'),
))
],
),
);
}
}
pubspec.yaml(仅复制相关内容(
name: cyber_education
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.12.0 <3.0.0"
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
cloud_firestore:
firebase_auth:
firebase_core:
firebase_auth_web:
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^1.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
在main
函数中,您需要在初始化Firebase之前放入await
关键字,因为它是一个异步操作。
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(); // 'await' at the beggining of the line
runApp(const MyApp());
}