Error: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

Error: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

我正在构建一个 Flutter 应用程序并且我已经集成了 Firebase,但是当我点击登录按钮时我总是收到这个错误。我遇到过有类似问题的人,但 none 似乎对我有用。我正在使用 VS Code 作为我的 IDE。我该如何解决这个问题?

这是我对每个文件的代码...

main.dart 文件


import 'login_screen.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      title: "FLUTTER-FIREBASE LOGIN APP",
      home: LoginScreen(),
    );
  }
}

login_screen.dart 文件

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

import 'profile_screen.dart';

class LoginScreen extends StatefulWidget {
  const LoginScreen({Key? key}) : super(key: key);

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  // Initialize Firebase App
  Future<FirebaseApp> _initializeFirebase() async {
    FirebaseApp firebaseApp = await Firebase.initializeApp();
    return firebaseApp;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        future: _initializeFirebase(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return const LoginForm();
          }
          return const Center(
            child: CircularProgressIndicator(),
          );
        },
      ),
    );
  }
}

class LoginForm extends StatefulWidget {
  const LoginForm({Key? key}) : super(key: key);

  @override
  State<LoginForm> createState() => _LoginFormState();
}

class _LoginFormState extends State<LoginForm> {
  // Login Function
  static Future<User?> loginUsingEmailPassword(
      {required String email,
      required String password,
      required BuildContext context}) async {
    FirebaseAuth auth = FirebaseAuth.instance;
    User? user;

    try {
      UserCredential userCredential = await auth.signInWithEmailAndPassword(
        email: email, 
        password: password,
      );
      user = userCredential.user;
    } on FirebaseAuthException catch (e) {
      if (e.code == "user-not-found") {
        print("No user found for that email");
      }
    }

    return user;
  }

  @override
  Widget build(BuildContext context) {
    // TextFielf Controller
    TextEditingController _emailController = TextEditingController();
    TextEditingController _passwordController = TextEditingController();

    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          const Text(
            "MyApp Title",
            style: TextStyle(
              color: Colors.black,
              fontSize: 28,
              fontWeight: FontWeight.bold,
            ),
          ),
          const Text(
            "Login to your App",
            style: TextStyle(
              color: Colors.black,
              fontSize: 44.0,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(
            height: 44.0,
          ),
          TextField(
            controller: _emailController,
            keyboardType: TextInputType.emailAddress,
            decoration: const InputDecoration(
                hintText: "enter email...",
                prefixIcon: Icon(
                  Icons.mail,
                  color: Colors.black,
                )),
          ),
          const SizedBox(
            height: 26.0,
          ),
          TextField(
            controller: _passwordController,
            obscureText: true,
            decoration: const InputDecoration(
              hintText: "enter password...",
              prefixIcon: Icon(
                Icons.lock,
                color: Colors.black,
              ),
            ),
          ),
          const SizedBox(
            height: 12.0,
          ),
          const Text(
            "Forgot Password?",
            style: TextStyle(
              color: Colors.blue,
            ),
          ),
          const SizedBox(
            height: 88.0,
          ),
          Container(
            width: double.infinity,
            child: RawMaterialButton(
              fillColor: const Color(0xFF0069FE),
              elevation: 0.0,
              padding: const EdgeInsets.symmetric(vertical: 20.0),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12.0),
              ),
              onPressed: () async {
                User? user = await loginUsingEmailPassword(
                    email: _emailController.text,
                    password: _passwordController.text,
                    context: context);
                print(user);

                if (user != null) {
                  Navigator.of(context).pushReplacement(
                    MaterialPageRoute(builder: (context) => const ProfileScreen()));
                }
              },
              child: const Text(
                "Login",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 18.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}

profile_screen.dart



class ProfileScreen extends StatefulWidget {
  const ProfileScreen({ Key? key }) : super(key: key);

  @override
  State<ProfileScreen> createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {
  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Center(
        child: Text("TO BE CONTINUED...!!!"),
      ),
    );
  }
}```



**This is the error message I get when I tap on the login button**

Error: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
    at Object.throw_ [as throw] (http://localhost:51555/dart_sdk.js:5067:11)
at firebase_core_web.FirebaseCoreWeb.new.app (http://localhost:51555/packages/firebase_core_web/firebase_core_web.dart.lib.js:285:23)
at Function.app (http://localhost:51555/packages/firebase_core/firebase_core.dart.lib.js:111:50)
at Function.get instance [as instance] (http://localhost:51555/packages/firebase_auth/firebase_auth.dart.lib.js:96:55)
at loginUsingEmailPassword (http://localhost:51555/packages/flutter_login_with_firebase_authentication/login_screen.dart.lib.js:1047:47)
    at loginUsingEmailPassword.next (<anonymous>)
    at runBody (http://localhost:51555/dart_sdk.js:40590:34)
    at Object._async [as async] (http://localhost:51555/dart_sdk.js:40621:7)
at Function.loginUsingEmailPassword (http://localhost:51555/packages/flutter_login_with_firebase_authentication/login_screen.dart.lib.js:1046:20)
at http://localhost:51555/packages/flutter_login_with_firebase_authentication/login_screen.dart.lib.js:1068:66
    at Generator.next (<anonymous>)
    at runBody (http://localhost:51555/dart_sdk.js:40590:34)
    at Object._async [as async] (http://localhost:51555/dart_sdk.js:40621:7)
at http://localhost:51555/packages/flutter_login_with_firebase_authentication/login_screen.dart.lib.js:1067:1029
at ink_well._InkResponseState.new.[_handleTap] (http://localhost:51555/packages/flutter/src/material/icon_button.dart.lib.js:40468:31)
at tap.TapGestureRecognizer.new.invokeCallback (http://localhost:51555/packages/flutter/src/gestures/recognizer.dart.lib.js:190:18)
    at LinkedMap.new.forEach (http://localhost:51555/dart_sdk.js:27679:11)
at pointer_router.PointerRouter.new.[_dispatchEventToRoutes] (http://localhost:51555/packages/flutter/src/gestures/pointer_router.dart.lib.js:110:29)
at pointer_router.PointerRouter.new.route (http://localhost:51555/packages/flutter/src/gestures/pointer_router.dart.lib.js:105:37)
at binding.WidgetsFlutterBinding.new.handleEvent (http://localhost:51555/packages/flutter/src/gestures/binding.dart.lib.js:364:26)
at binding.WidgetsFlutterBinding.new.dispatchEvent (http://localhost:51555/packages/flutter/src/gestures/binding.dart.lib.js:352:24)
at binding.WidgetsFlutterBinding.new.dispatchEvent (http://localhost:51555/packages/flutter/src/rendering/layer.dart.lib.js:5427:13)
at binding.WidgetsFlutterBinding.new.[_handlePointerEventImmediately] (http://localhost:51555/packages/flutter/src/gestures/binding.dart.lib.js:328:14)
at binding.WidgetsFlutterBinding.new.handlePointerEvent (http://localhost:51555/packages/flutter/src/gestures/binding.dart.lib.js:302:43)
at binding.WidgetsFlutterBinding.new.[_flushPointerEventQueue] (http://localhost:51555/packages/flutter/src/gestures/binding.dart.lib.js:292:14)
at binding.WidgetsFlutterBinding.new.[_handlePointerDataPacket] (http://localhost:51555/packages/flutter/src/gestures/binding.dart.lib.js:283:54)
    at Object.invoke1 (http://localhost:51555/dart_sdk.js:190405:7)
    at _engine.EnginePlatformDispatcher.__.invokeOnPointerDataPacket (http://localhost:51555/dart_sdk.js:171081:15)
    at _engine.PointerBinding.__.[_onPointerData] (http://localhost:51555/dart_sdk.js:171963:49)
    at http://localhost:51555/dart_sdk.js:172401:28
    at http://localhost:51555/dart_sdk.js:172357:16
    at loggedHandler (http://localhost:51555/dart_sdk.js:172062:11)

对于最新的 firebase 版本,您必须使用 Firebase Cli 来连接您的应用程序。

安装cli 先安装firebase cli

Firebase CLI 通过 npm 通过 运行 执行以下命令:

npm install -g firebase-tools

接下来,通过运行以下命令安装 FlutterFire CLI:

dart pub global activate flutterfire_cli

安装后,flutterfire 命令将全局可用。

在您的应用程序的根目录中,运行 配置命令:

flutterfire configure

配置命令将引导您完成多个过程:

  • 选择一个 Firebase 项目(基于 .firebaserc 文件或从 Firebase 控制台)。
  • 提示您要配置的平台(例如 Android、iOS、macOS 和 Web)。
  • 确定应该使用所选平台的哪些 Firebase 应用程序来提取配置。默认情况下,CLI 将尝试根据您当前的项目配置自动匹配 Firebase 应用程序。
  • 在您的项目中生成一个 firebase_options.dart 文件。

完成后,您现在可以导入生成的文件并将其提供给 initializeApp 方法: lib/main.飞镖 //导入生成的文件 import 'firebase_options.dart';

然后,通过 DefaultFirebaseOptions class:

中的 currentPlatform getter 提供当前平台选项

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);
..