我正在构建一个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()

自2020年8月17日起

所有Firebase版本都已更新,现在你必须在使用任何Firebase产品之前调用Firebase. initializeapp(),例如:

首先,所有Firebase产品现在都依赖于firebase_core版本(0.5.0+),因此您需要将其添加到pubspec中。yaml文件:

dependencies:
  flutter:
    sdk: flutter
  firebase_core : ^0.5.0
  # cloud_firestore: ^0.14.0 other firebase dependencies

然后你必须调用Firebase.initializeApp():

第一个例子

import 'package:flutter/material.dart';

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

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

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      // Initialize FlutterFire
      future: Firebase.initializeApp(),
      builder: (context, snapshot) {
        // Check for errors
        if (snapshot.hasError) {
          return SomethingWentWrong();
        }

        // Once complete, show your application
        if (snapshot.connectionState == ConnectionState.done) {
          return MyAwesomeApp();
        }

        // Otherwise, show something whilst waiting for initialization to complete
        return Loading();
      },
    );
  }
}

Firestore的第二个例子:

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: FirstRoute(title: 'First Route'),
    );
  }
}

class FirstRoute extends StatefulWidget {
  FirstRoute({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _FirstRouteState createState() => _FirstRouteState();
}

class _FirstRouteState extends State<FirstRoute> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("test"),
        ),
        body: FutureBuilder(
          future: getData(),
          builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return Column(
                children: [
                  Container(
                    height: 27,
                    child: Text(
                      "Name: ${snapshot.data.data()['name']}",
                      overflow: TextOverflow.fade,
                      style: TextStyle(fontSize: 20),
                    ),
                  ),
                ],
              );
            } else if (snapshot.connectionState == ConnectionState.none) {
              return Text("No data");
            }
            return CircularProgressIndicator();
          },
        ));
  }

  Future<DocumentSnapshot> getData() async {
    await Firebase.initializeApp();
    return await FirebaseFirestore.instance
        .collection("users")
        .doc("docID")
        .get();
  }
}

第三个例子:

在initState()中初始化它,然后调用setState(),后者将调用build()方法。

  @override
  void initState() {
    super.initState();
    Firebase.initializeApp().whenComplete(() { 
      print("completed");
      setState(() {});
    });
  }

第四个例子:

在调用WidgetsFlutterBinding.ensureInitialized()后在main()方法中初始化它;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

注意:你只需要调用initializeApp()一次


添加到pubspec.yaml firebase_core: 添加到main.dart 导入的包:firebase_core / firebase_core.dart '; 无效main() async { WidgetsFlutterBinding.ensureInitialized (); 等待Firebase.initializeApp (); runApp (MyApp ()); }


如果你离开应用程序到主屏幕时仍然有问题,你可以使用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();
  }
}

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


彼得的答案是完美的!但如果您的代码中仍然出现错误,并遵循Flutter Firebase代码实验室,请注意,这些教程截至2020年8月已过时,尚未更新。

你需要做很多其他的改变,比如:

将.data替换为.data() 用update替换updateData


首先,添加这个依赖:

firebase_core :

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

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

    //
    runApp(MyApp());
}

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

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


你需要添加await Firebase.initializeApp();这就是未来。在运行Firebase函数的dart文件中执行,如下所示:

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

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MaterialApp());
}

如果你遵循Peter的回答,仍然得到相同的错误,检查确保你的main函数中的任何其他东西都是在await Firebase.initializeApp()调用之后,如下所示:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
  FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
  runApp(MyApp());
}

你可以在主程序中初始化。dart文件,像这样使用FutureBuilder。

 future: Firebase.initializeApp(),

看看这个例子。

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

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      // Initialize FlutterFire
      future: Firebase.initializeApp(),
      builder: (context, snapshot) {
       return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'NEWSAPI.org',
          home: SplashScreen(),
       
          routes: <String, WidgetBuilder>{
            SPLASH_SCREEN: (BuildContext context) => SplashScreen(),
          },);
      },
    );
  }
}

在我的例子中,这是因为对于Web版本,您必须手动在index.html文件中添加东西,不仅是.js依赖项,还有配置。参见Web安装。

我们往往会忘记,对于大多数东西来说,Flutter是编译到目标的,而不需要改变任何特定于目标的东西,但在这种情况下,必须为每个目标添加配置。


颤动网与Firebase

如果您正在使用Flutter Web和Firebase,请确保在您的。/ Web /index.html的正文标签中安装了sdk

  <script src="https://www.gstatic.com/firebasejs/8.2.9/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.2.9/firebase-analytics.js"></script>

此外,确保使用index.html中的配置参数调用firebase.initializeApp(…)。

  <script>
    // Your web app's Firebase configuration
    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
    var firebaseConfig = {
      apiKey: "AIz...",
      authDomain: "...",
      databaseURL: "https://<project-name>.firebaseio.com",
      projectId: "...",
      storageBucket: "<project-name>.appspot.com",
      messagingSenderId: "...",
      appId: "...",
      measurementId: "..."
    };
    firebase.initializeApp(firebaseConfig);
    firebase.analytics();
  </script>

最后,按照Peter Haddad的回答配置firebase:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

对我来说,问题是我初始化它没有“等待”:

void main() async {
    WidgetsFlutterBinding.ensureInitialized();
    Firebase.initializeApp();

正确的做法是:

void main() async {
    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp();

自2017年8月以来,所有Firebase服务都已更新,因此在使用任何Firebase产品之前,您必须在主程序中调用Firebase. initializeapp(),例如:

如果您希望在flutter应用程序中使用firebase_core插件,则在您的pubspec中。Yaml文件添加firebase_core如下所示

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^1.19.1

然后调用Firebase.initializeApp():在你的应用中。如下所示:

import 'package:firebase_core/firebase_core.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

将此用于颤振:

   const firebaseConfig = {

    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
    };
   
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
  firebase.getAnalytics(app);

而不是这个

   const firebaseConfig = {

    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
    };

    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const analytics = getAnalytics(app);

你需要在main函数中添加await FirebaseApp.initializeApp(),记住要在main函数中添加await


我想评论一下。但这个问题有很多线索。 为了我的案子。

我在Firebase之前初始化了注入容器。 层级需要检查。

Hive.init(directory.path);
  await Firebase.initializeApp();// before
  await di.init();

只使用飞镖初始化(推荐)

在所有平台上使用CLI初始化Firebase。 不需要添加任何本地代码。 无需下载任何谷歌服务文件。

Install FlutterFire CLI dart pub global activate flutterfire_cli (Optional) Add the following line to your ~/.zshrc file and save it export PATH="$PATH":"$HOME/.pub-cache/bin" Run the configure: flutterfire configure Press enter to configure all the platforms You should now have a lib/firebase_options.dart file. Import this file in your main.dart and use Firebase.initializeApp. import 'firebase_options.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); // This is the last thing you need to add. await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); runApp(...); }


迁移到仅dart初始化:

如果您已经有一个现有的应用程序,您可以通过以下方式迁移它。

Android: 删除谷歌服务。Json文件从<flutter-project>/android/app: 删除<flutter-project>/android/build中的以下行。gradle文件 删除<flutter-project>/android/app/build中的以下行。gradle文件 iOS 打开< flutter-project > / ios /跑步者。在Xcode中删除GoogleService-Info文件。来自Runner的plist文件。 macOS 打开< flutter-project > / macos /跑步者。在Xcode中删除GoogleService-Info文件。来自Runner的plist文件。

更多信息可以在这里找到


如果你正确设置了Firebase,不要忘记添加

等待

之前

Firebase.initializeApp ();

这就是异常的主要问题。

等待Firebase.initializeApp ();


就我而言,我为现有项目添加了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 = {
   ....
   }

这是2022年初始化firebase的方法

首先,使用此链接==>安装FlutterFire 颤振消防安装环节

安装FlutterFire之后,需要在lib/main中添加这些代码行。飞镖文件

  import 'package:firebase_core/firebase_core.dart';
  import 'firebase_options.dart';  

然后编辑你的主函数如下所示

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

这在将来可能会改变,因此请参考下面的最新实现参考

初始化FlutterFire #


初始化firebase选项

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

像这样


我需要用FlutterFire cli重新配置Firebase应用程序。

https://firebase.flutter.dev/docs/cli

通过NPM Install -g firebase-tools安装firebase-tool 安装flutterfire cli: dart pub global activate flutterfire_cli 运行此命令在项目中配置firebase: flutterfire configure

按上述链接进行初始化,如下所示:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  runApp(const MyApp());
}

当它等待调用时,应用程序将显示启动屏幕,Firebase可能无法初始化,因此我接下来用另一个FutureBuilder作为主屏幕,以确保在使用FirebaseAuth之前,Firebase应用程序已初始化。

home: FutureBuilder(
          future: Firebase.initializeApp(),
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return Text(snapshot.error.toString(),
                  style: TextStyle(fontSize: 10));
            }

            if (snapshot.connectionState == ConnectionState.done) {
              return StreamBuilder(
                stream: FirebaseAuth.instance.authStateChanges(),
                builder: (context, snapshot) {
                  return snapshot.hasData ? Home() : AuthPage();
                },
              );
            } else {
              return Text('');
            }
          })

从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文档。


如果您正在工作的项目中预先配置了firebase_core,然后尝试添加新包,它将给出该错误。

您必须首先从pubsec中删除firebase_core:。Yaml,然后保存文件并通过flutter pub add firebase_core和flutterfire configure重新配置它。

然后您可以添加任何新的包。


在大多数情况下,此问题是在将项目从旧的Flutter版本升级到零安全后观察到的。应该检查以下内容:

确保在pubspecc .yaml中有firebase-core

导入firebase核心:

import 'package:firebase_core/firebase_core.dart';

在任何调用之前Init Firebase -最好在main内部。Dart,因此它在任何其他实现之前执行:

WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

来自官方文件。


初始化firebase选项

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

确保您使用的是正确的/官方版本的firebase包。

我用的是:

firebase_core_dart: <version-number>

在:https://pub.dev/packages/firebase_core_dart

而不是官方

firebase_core: <版本号>

在https://pub.dev/packages/firebase_core

使用第一个选项,我得到了初始化时使用:

await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  ).whenComplete(
      () => print('FIREBASE INITIALIZED================>'));

但是验证失败,并出现OP描述的错误消息。


试试下面的代码。它将同时解决IOS和Android的问题。

import 'dart:io';
import 'package:firebase_core/firebase_core.dart';

    void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  if (Platform.isIOS) {
    await Firebase.initializeApp(
      options: const FirebaseOptions(
          apiKey: "found in your google service-info.plist",
          appId: "found in your google service-info.plist",
          messagingSenderId: "found in firebase",
          projectId: "found in firebase"),
    );
  } else {
    await Firebase.initializeApp();
  }
  runApp(const MyApp());
}