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"),
)
)
)
);
}
}
다음은 throw 된 예외입니다.
══╡ 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.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()
한 번만 전화 하면됩니다.
답변
-
pubspec.yaml에 추가
firebase_core :
-
main.dart에 추가
import 'package:firebase_core/firebase_core.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); }
답변
firebase를 flutter 앱과 연결하려면 사용하기 전에 firebase를 초기화해야합니다. 아래와 같이 선언하면 문제 해결에 도움이됩니다.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
답변
이에 대한 간단한 해결책은 다음과 같습니다.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp(),);
}
답변
@peter의 대답은 완벽합니다 !! 하지만 여전히 코드에서 오류가 발생하고 flutter firebase codelab을 따르는 경우 해당 자습서는 2020 년 8 월 기준으로 구식이며 아직 업데이트되지 않았습니다.
다음과 같은 다른 많은 변경을 수행해야합니다.
- 교체
.data
로.data()
- 교체
updateData
로update
이것이 나 같은 초보자에게 도움이되기를 바랍니다.
답변
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
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();
}
}