尚未创建Firebase应用程序'[DEFAULT]'-在Flutter和Firebase中调用Firebase.initializeApp()


181

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

Answers:


408

自2020年8月17日起

所有Firebase版本均已更新,现在您必须Firebase.initializeApp()使用任何Firebase产品才能致电,例如:

首先,所有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(() {});
    });
  }

第四例:

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

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

注意:您只需拨打initializeApp()一次


47
第四个例子应该是它。只记得添加异步。我想知道延迟是否明显。
莱德

15
烨第4例子是最好的,只是想显示所有的方式,第二也不错,因为你可以得到初始化在同一FutureBuilder从公司的FireStore或实时数据库中的第一个数据之前
彼得·哈达德

5
谢谢,它可以使用#4。但是,如果您按“后退”按钮,则当您返回应用程序时,它会说“没有创建Firebase应用程序'[DEFAULT]'-调用Firebase.initializeApp()”,即使它在main()中也是如此
八位位组

4
@MichaelDiCioccio flutter框架使用微件绑定来与flutter引擎进行交互。调用时,ensureInitislized它会创建的实例,Widgetbinding并且由于Firebase.initializeApp()需要使用平台渠道来调用本机,因此您需要初始化绑定。api.flutter.dev/flutter/widgets/WidgetsFlutterBinding/…(平台通道在flutter引擎中)
Peter Haddad

2
#4似乎不适用于Providers(与最初的错误消息相同)
被抛弃

73
  1. 添加到pubspec.yaml

    firebase_core :
    
  2. 添加到main.dart

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

1
这些行将给出:lib / main.dart:6:9:错误:找不到Getter:'Firebase'。等待Firebase.initializeApp(); ^^^^^^^^
卡斯帕L. Palgi

我忘了给firebase_core打假。做过某事。现在:这些行将给出:E / flutter(24294):[ERROR:flutter / lib / ui / ui_dart_state.cc(166)]未处理的异常:[core / no-app]没有Firebase应用程序'[DEFAULT]'创建-调用Firebase.initializeApp()
Kaspar L. Palgi '20

此处在firebase.google.com/support/release-notes/android中表示:不再需要Firebase Android库firebase-core。该SDK包括适用于Google Analytics(分析)的Firebase SDK。现在,要使用Google Analytics(分析)或推荐使用Google Analytics(分析)的产品(请参见下表),您需要明确添加Google Analytics(分析)依赖项:com.google.firebase:firebase-analytics:17.5.0或com.google.firebase:firebase -analytics-ktx:17.5.0。
卡斯珀·帕尔吉

如果initializeApp崩溃了怎么办?应用程序将无法启动。我没有发现有关此可能问题的任何信息。
鲍里斯·萨利莫夫

@BorisSalimov因为initializeApp()是异步调用,所以即使失败,该应用程序仍会启动
20rw

12

如果要将Firebase与Flutter应用程序连接,则需要先初始化Firebase,然后再使用它。您可以按照以下说明声明它,这将帮助您解决问题

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

在视频中,您将详细了解该错误


它向我显示了一个错误-构建Builder时引发了以下NoSuchMethodError:I / flutter(5612):在null上调用了“ then”方法。I / flutter(5612):接收方:空I / flutter(5612):尝试过的呼叫:then(关闭:(动态)=> Null)
Abir Ahsan

请按照链接中的视频操作,您的问题将得到解决。如果仍然遇到错误,请告诉我。
拉朱古达


6

@彼得的答案是完美的!但是,如果仍然在代码中出现错误,并遵循火爆的Firebase代码实验室,请注意,这些教程到2020年8月已过时,尚未更新。 您需要进行其他许多更改,例如:

  • 替换.data.data()
  • 替换updateDataupdate

希望这可以对像我这样的新手有所帮助。


6

如果您遵循Peter的回答并且仍然遇到相同的错误,请检查以确保main函数中的其他内容在await Firebase.initializeApp()调用后出现,如下所示:

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

谢谢。@彼得的回答帮助,虽然
Kobby折扣

4

如果您在将应用程序移至主屏幕时仍然遇到问题,则可以.dart使用firebase将其添加到任何文件中:

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

有关更多信息,请单击此链接


1
即使执行与文档相同的步骤,也出现错误。这是错误No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() 。我已经在有状态小部件中初始化了Firebase。
Vikrant Agrahari

3

1添加此依赖项:

firebase_core :

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

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

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

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


2

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

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

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MaterialApp());
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.