我正在构建一个Flutter应用程序,我已经集成了Firebase,但当我点击一个按钮注册,登录或注销时,我一直得到这个错误。我看到其他人也问过同样的问题,但似乎没有一个对我有用。我正在使用Flutter和Android Studio。我该如何解决这个问题?

这是我的代码的摘录

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.red,
      body: Center(
        child: Container(
          child: RaisedButton(
            onPressed: () {
              FirebaseAuth.instance.signOut().then((value) {
                Navigator.pushReplacement(
                    context,
                    MaterialPageRoute(
                        builder: (context) =>
                            LoginScreen()));
              });
            },
            child: Text("Logout"),
          )
        )
      )
    );
  }
}

下面是抛出的异常

══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
The following FirebaseException was thrown while handling a gesture:
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

When the exception was thrown, this was the stack:

#0      MethodChannelFirebase.app (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:118:5)
#1      Firebase.app (package:firebase_core/src/firebase.dart:52:41)
#2      FirebaseAuth.instance (package:firebase_auth/src/firebase_auth.dart:37:47)
#3      _HomeScreenState.build.<anonymous closure> (package:cosytok/screens/home.dart:20:28)
#4      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19)
#5      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1098:38)
#6      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
#7      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
#8      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
#9      BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:219:7)
#10     PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:477:9)
#11     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:78:12)
#12     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:124:9)
#13     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
#14     PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:122:18)
#15     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:108:7)
#16     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:220:19)
#17     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
#18     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
#19     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
#20     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
#24     _invoke1 (dart:ui/hooks.dart:267:10)
#25     _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)
(elided 3 frames from dart:async)

Handler: "onTap"
Recognizer:
  TapGestureRecognizer#f0104
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════
The following FirebaseException was thrown while handling a gesture:
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

当前回答

从Flutter 2.8版本开始,现在可以在使用Firebase的所有平台上从Dart初始化FlutterFire。initializeApp函数。有一种更简单快捷的方法来初始化一个firebase项目,而不是从firebase控制台下载.json和.plist文件并将它们放入您的Flutter项目文件夹中,这可能会导致一些警告。这是我经历过几次的问题,下面是我解决它的方法。

在firebase控制台步骤中创建项目并在这里安装firebase CLI后,请继续执行以下步骤:

如果已经使用flutterfire配置配置了firebase项目,则可以跳过步骤1并跳转到步骤4。

从您的项目根终端,命令: $ flutterfire配置 //需要Firebase命令行才能正常工作。 按回车键或回车键选择firebase项目。 插入bundle ID。你可以通过右键单击ios文件夹>,然后单击“在xcode中打开”来获得。Bundle Identifier将出现在右边的白色面板中,当提示时,你必须在终端中手动输入。

**如果您已经安装了firebase_core插件,请继续执行步骤5。**

Install the latest version of the firebase_core plugin by running this command from your project root directory: $ flutter pub add firebase_core // Adds to pubspec.yaml Add imports to the main file: import 'package:firebase_core/firebase_core.dart'; // import 'firebase_options.dart'; // Generated file Update your main function to initialize firebase with this async function: Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); runApp(const YourAppName()); }

有关更多信息,请参阅FlutterFire文档。

其他回答

就我而言,我为现有项目添加了web支持。 唯一能解决这个问题的是,

在web/index.html文件中

将所有firebase sdk导入版本从9.6.6更改为8.10.0

片段

<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app-check.js"></script>  
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-firestore.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-auth.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-storage.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js"></script>
 <script>
  var firebaseConfig = {
   ....
   }

初始化firebase选项

void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform).catchError((e){
  print(" Error : ${e.toString()}");
});
}

像这样

初始化firebase选项

void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform).catchError((e){
    print(" Error : ${e.toString()}");
  });
}

首先,添加这个依赖:

firebase_core :

第二:在项目main函数中,添加这两行,并使函数async:

void main() async {
    // These two lines
    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp();

    //
    runApp(MyApp());
}

现在您可以在项目中的任何文件或小部件中正常使用Firebase。

FutureBuilder小部件也可以工作,但每次要访问Firebase时都必须添加它。

如果你离开应用程序到主屏幕时仍然有问题,你可以使用Firebase将此添加到任何.dart文件中:

class App extends StatelessWidget {

  final Future<FirebaseApp> _initialization = Firebase.initializeApp();

  @override
  Widget build(BuildContext context) {

或者在StatefulWidget的情况下:

import 'package:flutter/material.dart';

// Import the firebase_core plugin
import 'package:firebase_core/firebase_core.dart';

void main() {
  runApp(App());
}

class App extends StatefulWidget {
  _AppState createState() => _AppState();
}

class _AppState extends State<App> {
  // Set default `_initialized` and `_error` state to false
  bool _initialized = false;
  bool _error = false;

  // Define an async function to initialize FlutterFire
  void initializeFlutterFire() async {
    try {
      // Wait for Firebase to initialize and set `_initialized` state to true
      await Firebase.initializeApp();
      setState(() {
        _initialized = true;
      });
    } catch(e) {
      // Set `_error` state to true if Firebase initialization fails
      setState(() {
        _error = true;
      });
    }
  }

  @override
  void initState() {
    initializeFlutterFire();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // Show error message if initialization failed
    if(_error) {
      return SomethingWentWrong();
    }

    // Show a loader until FlutterFire is initialized
    if (!_initialized) {
      return Loading();
    }

    return MyAwesomeApp();
  }
}

欲了解更多信息,请查看此链接。