没有Firebase应用'已创建-在Flutter和Firebase中调用Firebase. initializeapp ()

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

这是我的代码的摘录

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()
298855 次浏览

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

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

如果你离开应用程序到主屏幕时仍然有问题,你可以使用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();,它是一个Future。在运行Firebase函数的dart文件中执行,如下所示:

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


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

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

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

你也可以像这样使用FutureBuildermain.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(),
},);
},
);
}
}

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

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

颤动网与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>

最后,按照彼得·哈达德的回答是中的描述配置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。
  • 不需要添加任何本地代码。

  • 不需要下载任何谷歌服务文件。

  1. 安装FlutterFire CLI

    dart pub global activate flutterfire_cli
    
  2. (可选)添加以下行到你的~/.zshrc文件并保存它

    export PATH="$PATH":"$HOME/.pub-cache/bin"
    
  3. 运行configure:

    flutterfire configure
    
  4. enter配置所有平台

    enter image description here

  5. 你现在应该有一个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(...);
    }
    

迁移到仅dart初始化:

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

  • < h3 > Android:
    1. <flutter-project>/android/app中删除google-services.json文件:

      enter image description here

    2. 删除<flutter-project>/android/build.gradle文件中的以下行

      enter image description here

    3. 删除<flutter-project>/android/app/build.gradle文件中的以下行

      enter image description here

  • < h3 > iOS

    在Xcode中打开<flutter-project>/ios/Runner.xcworkspace文件,并从Runner中删除GoogleService-Info.plist文件。

    enter image description here

  • < h3 > macOS

    在Xcode中打开<flutter-project>/macos/Runner.xcworkspace文件,并从Runner中删除GoogleService-Info.plist文件。

    enter image description here

更多信息可以找到在这里

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

await

之前

Firebase.initializeApp();

这就是异常的主要问题。

等待Firebase.initializeApp ();

在我的情况下,我添加了web支持我的现有的项目。 解决这个问题的是

web/index.html文件中

所有firebase SDK导入verison9.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 ==> 颤振消防安装环节 < / p >

安装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

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

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

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

由于它的等待调用,应用程序将显示启动屏幕和Firebase可能无法初始化,因此我接下来继续使用另一个FutureBuilder for home屏幕,以确保Firebase应用程序在我使用FirebaseAuth之前已初始化。

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

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

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

  1. 从项目根终端,命令:

      $ flutterfire configure
    // This requires the Firebase CLI to work.
    
  2. 通过回车键选择firebase项目。

  3. 插入bundle ID。你可以通过右键点击ios文件夹>然后点击“在xcode中打开”。Bundle Identifier将出现在右边的白色面板中,当提示时,你必须在终端中手动输入。

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

  1. 在你的项目根目录下运行以下命令安装最新版本的firebase_core插件:

     $ flutter pub add firebase_core  // Adds to pubspec.yaml
    
  2. 在主文件中添加导入:

     import 'package:firebase_core/firebase_core.dart'; //
    import 'firebase_options.dart'; // Generated file
    
  3. 更新你的main函数来初始化firebase:

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

更多信息请参见FlutterFire文档

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

你必须首先从pubsec中删除firebase_core:。然后保存文件并通过flutter pub add firebase_coreflutterfire 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: <version-number>

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