没有创建 Firebase 应用 [DEFAULT] = 调用 Firebase.initializeApp()

Posted

技术标签:

【中文标题】没有创建 Firebase 应用 [DEFAULT] = 调用 Firebase.initializeApp()【英文标题】:No Firebase App [DEFAULT] has been created = call Firebase.initializeApp() 【发布时间】:2021-12-29 05:50:14 【问题描述】:

所以我遇到了这个错误,我一直在尝试使用可用资源(包括 ***)来解决这个问题。没有任何效果,我仍然收到相同的错误“”

这是我的 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

【问题讨论】:

【参考方案1】:

在您的 main 函数中,您需要在初始化 Firebase 之前添加 await 关键字,因为它是一个异步操作。

void main() async 
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();  // 'await' at the beggining of the line
  runApp(const MyApp());

【讨论】:

我用过,但我有一个空白屏幕,没有任何反应。 为什么您的 firebaseConfig 中充满了“xxxx”?您需要将真实数据放在那里。 我认为这是机密 好的,我明白了。只是要求把事情弄清楚。你不需要在这里展示它。 关于我应该做什么的任何提示?如果我使用 await 没有任何反应,只会出现一个空白屏幕。难道我做错了什么?我没有其他线索应该如何处理这个项目......

以上是关于没有创建 Firebase 应用 [DEFAULT] = 调用 Firebase.initializeApp()的主要内容,如果未能解决你的问题,请参考以下文章

没有创建 Firebase 应用“[DEFAULT]” - 在 Flutter 和 Firebase 中调用 Firebase.initializeApp()

没有创建 Firebase 应用“[DEFAULT]” - 即使调用 Firebase.InitializeApp(),错误仍然存​​在

Firebase:使用预留托管 URL 时未创建 Firebase 应用“[DEFAULT]”

如何解决 Firebase:没有创建 Firebase App '[DEFAULT]' - 调用 Firebase App.initializeApp() (app/no-app)

Flutter 和 Firebase:没有创建 Firebase App '[DEFAULT]' - 调用 Firebase App.initializeApp() (app/no-app)

FirebaseError:Firebase:未创建 Firebase 应用“[DEFAULT]” - 调用 Firebase App.initializeApp() (app/no-app)。 颤动