当前位置: 首页 > 知识库问答 >
问题:

未创建Firebase应用程序“[DEFAULT]”-在Flutter和Firebase中调用Firebase.InitializeApp()

蓝昊天
2023-03-14

我正在构建一个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个答案

公孙令秋
2023-03-14

所有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();
      },
    );
  }
}
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());
}
 类似资料:
  • 我有一个连接到两个应用程序的firebase数据库,一个是iOS应用程序,另一个是在Node.js中编码的web应用程序,这是一个将数据设置到数据库的基本算法。当我运行我遇到的算法时- 错误:未创建Firebase应用程序“[DEFAULT]”-调用Firebase App.InitializeApp()。错误(本机)在R处(/users/dd/desktop/code/node/node_mod

  • 我有点明白这个错误,但不管我怎么说,它都不起作用...我试图从FireBase中只返回一个字符串和一个数字值。我也做了所有的要求。android文件夹中的build.graddle和android/App文件夹中的build.gradle。一切。除此之外,我还做了:cloud_firestore: 对pubspec.yaml的依赖关系。现在我的main.dart看起来是这样的,但是它给出了太多的错

  • 我正在使用Firebase,并测试在应用程序处于后台时从服务器向应用程序发送通知。通知发送成功,它甚至出现在设备的通知中心上,但是当通知出现或者即使我单击它,我的FCMessagingService中的onMessageReceived方法也从未被调用。 当我在应用程序处于前台时进行测试时,调用了onMessageReceived方法,所有工作都很好。该问题发生在应用程序在后台运行时。 这是有意为

  • 我清楚地阅读了很多关于firebase推送通知行为的文档。当我的应用程序位于后台时,我可以在系统托盘上看到通知,但当应用程序位于前台时,不会触发“收到消息时”的回调。我可以看到我的应用程序上收到消息的日志。我试着用数据负载和没有数据负载的应用服务器进行通话。我的应用服务器正在使用php脚本来触发fcm API。下面是我正在使用的php脚本 以下是我在我的Android应用程序中使用的服务

  • 我试图完成的是解析来自Remotemessage的传入数据,并根据自定义标记对其进行不同的处理。例如,如果数据映射包含一个名为“my_custom_tag”的字段,我希望完全覆盖弹出的标准firebase消息并编写一个自定义消息。 问题是,当应用程序在后台运行时,我放入onMessageReceived的任何代码都不会被触发。当应用程序在前台运行时,它工作得很好,但如果应用程序在后台,它将不会检测

  • 我正在构建一个flatter应用程序,并且我已经集成了Firebase,但是当我单击登录按钮时,我一直会遇到这个错误。我遇到过有类似问题的人,但似乎没有一个适合我。我使用VS代码作为我的IDE。我如何解决这个问题? 这是我每个文件的代码。。。 main.dart文件 登录屏幕。dart文件 profile_屏幕。飞奔