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

Posted

技术标签:

【中文标题】没有创建 Firebase 应用“[DEFAULT]” - 在 Flutter 和 Firebase 中调用 Firebase.initializeApp()【英文标题】:No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() in Flutter and Firebase 【发布时间】:2020-12-09 10:19:51 【问题描述】:

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

【问题讨论】:

【参考方案1】:

自 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()一次

【讨论】:

应该是第四个例子。只要记住添加异步。我想知道延迟是否明显。 是的,第 4 个示例是最好的示例,只是想展示所有方法,第二个也很好,因为您可以在从同一 FutureBuilder 中的 firestore 或实时数据库获取第一个数据之前进行初始化跨度> 谢谢,它可以使用#4。但是如果你按下“返回”按钮,当你返回应用程序时,它会说同样的事情“没有创建 Firebase 应用程序'[DEFAULT]' - 调用 Firebase.initializeApp()”,即使它在 main() @MichaelDiCioccio Flutter 框架使用小部件绑定来与 Flutter 引擎进行交互。当您调用ensureInitislized 时,它会创建Widgetbinding 的实例,并且由于Firebase.initializeApp() 需要使用平台通道来调用本机,因此您需要初始化绑定。 api.flutter.dev/flutter/widgets/WidgetsFlutterBinding/…(平台频道在flutter引擎中) #4 似乎不适用于提供者(与最初的错误消息相同)【参考方案2】:

    添加到 pubspec.yaml

    firebase_core :
    

    添加到 main.dart

    import 'package:firebase_core/firebase_core.dart';
    
    void main() async 
       WidgetsFlutterBinding.ensureInitialized();
       await Firebase.initializeApp();
       runApp(MyApp());
    
    

【讨论】:

这些行将给出:lib/main.dart:6:9: Error: Getter not found: 'Firebase'。等待 Firebase.initializeApp(); ^^^^^^^^ 我忘记导入 firebase_core。做过某事。现在:这些行将给出: E/flutter (24294): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: [core/no-app] No Firebase App '[DEFAULT]' has been创建 - 调用 Firebase.initializeApp() 这里firebase.google.com/support/release-notes/android 说:不再需要Firebase Android 库firebase-core。此 SDK 包括用于 Google Analytics 的 Firebase SDK。现在,要使用 Analytics 或推荐使用 Analytics 的产品(见下表),您需要显式添加 Analytics 依赖项:com.google.firebase:firebase-analytics:17.5.0 或 com.google.firebase:firebase -analytics-ktx:17.5.0. 如果initializeApp会崩溃怎么办?应用程序不会启动。我没有发现任何关于这个可能的问题。 @BorisSalimov 因为initializeApp() 是异步调用,所以即使失败,应用程序仍然会启动【参考方案3】:

如果您将应用程序留在主屏幕时仍然存在问题,您可以使用 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();
  

更多信息,请查看this link。

【讨论】:

即使我执行与文档相同的过程,我也会收到错误消息。这是错误No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() 。我已经在有状态小部件中初始化了 Firebase。【参考方案4】:

Peter's answer 是完美!!但是如果您的代码中仍然出现错误并遵循Flutter Firebase codelab,请注意这些教程截至 2020 年 8 月已过时且尚未更新。

您需要进行许多其他更改,例如:

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

【讨论】:

【参考方案5】:

首先,添加这个依赖:

firebase_core :

第二:在项目主函数中,添加这两行,使函数异步:

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

    //
    runApp(MyApp());

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

FutureBuilder 小部件也可以使用,但您必须在每次要访问 Firebase 时添加它。

【讨论】:

【参考方案6】:

您需要添加await Firebase.initializeApp();,即Future。在运行 Firebase 函数的 dart 文件中执行此操作,如下所示:

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

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

【讨论】:

【参考方案7】:

如果您关注了Peter's answer,但仍然遇到同样的错误,请检查以确保main 函数中的其他内容出现在await Firebase.initializeApp() 调用之后,如下所示:

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

【讨论】:

【参考方案8】:

您也可以使用 FutureBuilderma​​in.dart 文件中进行初始化。

 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(),
          ,);
      ,
    );
  

【讨论】:

解释一下。例如,想法/要点是什么?请通过editing your answer 回复,而不是在 cmets 中(without "Edit:"、"Update:" 或类似的 - 答案应该看起来像是今天写的)。【参考方案9】:

在我的情况下,这是因为对于 Web 版本,您必须在 index.html 文件中手动添加内容,不仅是 .js 依赖项,还有配置。请参阅Web Installation

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

【讨论】:

【参考方案10】:

Flutter Web 与 Firebase

如果您将 Flutter Web 与 Firebase 一起使用,请确保您在 ./web/index.htmlbody 标记中安装了 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's answer中的描述配置firebase:

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

【讨论】:

那是不安全地将敏感数据放入.html @user7856586 在这种情况下你会说什么是敏感数据? 对不起,我的意思是我们也应该修复 Gcloud 上的规则,因为将裸数据存储在 html 文件中是不安全的。看here【参考方案11】:

对我来说问题是我在没有“等待”的情况下对其进行了初始化:

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

正确的做法是:

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

【讨论】:

【参考方案12】:

自 2017 年 8 月起,所有 Firebase 服务都已更新,因此您必须先在 main 中调用 Firebase.initializeApp(),然后才能使用任何 Firebase 产品,例如:

如果您想在 Flutter 应用程序中使用 firebase_core 插件,请在您的 pubspec.yaml 文件中添加 firebase_core,如下所示

dependencies:
  flutter:
    sdk: flutter
  firebase_core : ^1.2.0

然后在您的应用中调用 Firebase.initializeApp():。与以下内容相同:

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

【讨论】:

【参考方案13】:

用这个来颤振:

   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);

【讨论】:

【参考方案14】:

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

【讨论】:

【参考方案15】:

ma​​in.dart文件中添加依赖import 'package:firebase_core/firebase_core.dart';并调用Firebase.initializeApp()方法如下:

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

//modify the main method
void main() async 
    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp();
    runApp(const MyApp());

【讨论】:

【参考方案16】:

我想发表评论。但是这个问题有很多线索。 就我而言。

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

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

【讨论】:

【参考方案17】:

使用 CLI 在所有平台上初始化 Firebase

    安装 FlutterFire CLI

    dart pub global activate flutterfire_cli
    

    (可选)将以下行添加到您的~/.zshrc 文件并保存

    export PATH="$PATH":"$HOME/.pub-cache/bin"
    

    运行configure:

    flutterfire configure
    

    enter配置所有平台

    您现在应该有一个lib/firebase_options.dart 文件。将此文件导入您的main.dart 并使用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(...);
    
    

【讨论】:

以上是关于没有创建 Firebase 应用“[DEFAULT]” - 在 Flutter 和 Firebase 中调用 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)。 颤动