Flutter: Unable to Firebase.initializeApp() Firebase authentication services
Created a new class to manage sign-in methods in one place, a Dart class with no flutter Widget.
It gives errors about FIREBASE INITIALIZATION after following https://firebase.flutter.dev/docs/overview/#initializing-flutterfire.
Error: No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp(). _firebaseAuth is useless without it.
Full sample project here: https://github.com/dashanan13/time_tracker_flutter_course.git
Please help, this is frustrating.
StackTrace:
Launching lib\main.dart on Android SDK built for x86 in debug mode...
Running Gradle task 'assembleDebug'...
Parameter format not correct -
✓ Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
Waiting for Android SDK built for x86 to report its views...
Debug service listening on ws://127.0.0.1:60201/mhWPMlMla50=/ws
Syncing files to device Android SDK built for x86...
E/GraphResponse(20120): {HttpStatus: 404, errorCode: 803, subErrorCode: -1, errorType: OAuthException, errorMessage: (#803) Cannot query users by their username (CHANGE-ME)}
E/GraphResponse(20120): {HttpStatus: 404, errorCode: 803, subErrorCode: -1, errorType: OAuthException, errorMessage: (#803) Cannot query users by their username (CHANGE-ME)}
W/AnalyticsUserIDStore(20120): initStore should have been called before calling setUserID
W/UserDataStore(20120): initStore should have been called before calling setUserID
D/EGL_emulation(20120): eglMakeCurrent: 0xd731a9c0: ver 2 0 (tinfo 0xd730f730)
E/GraphResponse(20120): {HttpStatus: 404, errorCode: 803, subErrorCode: -1, errorType: OAuthException, errorMessage: (#803) Cannot query users by their username (CHANGE-ME)}
I/OpenGLRenderer(20120): Davey! duration=2122ms; Flags=1, IntendedVsync=172506915033871, Vsync=172506948367203, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=172506964470903, AnimationStart=172506964518803, PerformTraversalsStart=172506964557703, DrawStart=172508239012703, SyncQueued=172508239844803, SyncStart=172508241475003, IssueDrawCommandsStart=172508241758403, SwapBuffers=172508678528903, FrameCompleted=172509039559203, DequeueBufferDuration=21745000, QueueBufferDuration=142000,
I/Choreographer(20120): Skipped 129 frames! The application may be doing too much work on its main thread.
E/GraphResponse(20120): {HttpStatus: 404, errorCode: 803, subErrorCode: -1, errorType: OAuthException, errorMessage: (#803) Cannot query users by their username (CHANGE-ME)}
I/asics_for_dars(20120): Background young concurrent copying GC freed 26775(1377KB) AllocSpace objects, 9(360KB) LOS objects, 41% free, 2468KB/4219KB, paused 131.474ms total 1.416s
D/EGL_emulation(20120): eglMakeCurrent: 0xea67f940: ver 2 0 (tinfo 0xd3e265e0)
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following FirebaseException was thrown building LandingPage(dirty, dependencies:
[InheritedProvider<AuthBase>]):
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
The relevant error-causing widget was:
LandingPage
file:///C:/Users/.../basics_for_darsh/lib/main.dart:68:41
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 Auth.onAuthStateChanged (package:basics_for_darsh/utilities/auth.dart:47:35)
#4 LandingPage.build (package:basics_for_darsh/utilities/landingPage.dart:18:22)
#5 StatelessElement.build (package:flutter/src/widgets/framework.dart:4620:28)
#6 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4546:15)
#7 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#8 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4525:5)
#9 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4520:5)
... Normal element mounting (132 frames)
#141 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
#142 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5991:32)
... Normal element mounting (287 frames)
#429 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
#430 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
#431 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1174:16)
#432 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1145:5)
#433 RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:1087:17)
#434 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2620:19)
#435 RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1086:13)
#436 WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:927:7)
#437 WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> (package:flutter/src/widgets/binding.dart:908:7)
(elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch)
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following FirebaseException was thrown building LandingPage(dirty, dependencies: [InheritedProvider<AuthBase>]):
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
The relevant error-causing widget was:
LandingPage file:///C:/Users/.../basics_for_darsh/lib/main.dart:68:41
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 Auth.onAuthStateChanged (package:basics_for_darsh/utilities/auth.dart:47:35)
#4 LandingPage.build (package:basics_for_darsh/utilities/landingPage.dart:18:22)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
E/GraphResponse(20120): {HttpStatus: 404, errorCode: 803, subErrorCode: -1, errorType: OAuthException, errorMessage: (#803) Cannot query users by their username (CHANGE-ME)}
E/GraphResponse(20120): {HttpStatus: 404, errorCode: 803, subErrorCode: -1, errorType: OAuthException, errorMessage: (#803) Cannot query users by their username (CHANGE-ME)}
Firebase authentication is useless without initialization. Error: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() Please help.
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_facebook_login/flutter_facebook_login.dart';
import 'package:google_sign_in/google_sign_in.dart';
class MyUser {
MyUser({@required this.uid});
final String uid;
}
abstract class AuthBase {
Stream<MyUser> get onAuthStateChanged;
Future<MyUser> currentUser();
Future<MyUser> signInAnonymously();
Future<MyUser> signInWithGoogle();
Future<void> signOut();
}
class Auth implements AuthBase {
var _initialization,_firebaseAuth;
Auth(){
_intializeMe();
_firebaseAuth = FirebaseAuth.instance;
}
_intializeMe() async {
FirebaseApp _initialization = (await Firebase.initializeApp());
}
MyUser _userFromFirebase(User user) {
if (user == null) {
return null;
}
return MyUser(uid: user.uid);
}
@override
Stream<MyUser> get onAuthStateChanged {
return _firebaseAuth.authStateChanges().map(_userFromFirebase);
}
@override
Future<MyUser> currentUser() async {
final user = await _firebaseAuth.currentUser;
return _userFromFirebase(user);
}
@override
Future<MyUser> signInAnonymously() async {
final authResult = await _firebaseAuth.signInAnonymously();
return _userFromFirebase(authResult.user);
}
@override
Future<MyUser> signInWithGoogle() async {
final googleSignIn = GoogleSignIn();
final googleAccount = await googleSignIn.signIn();
if (googleAccount != null) {
final googleAuth = await googleAccount.authentication;
if (googleAuth.accessToken != null && googleAuth.idToken != null) {
final authResult = await _firebaseAuth.signInWithCredential(
GoogleAuthProvider.credential(
idToken: googleAuth.idToken,
accessToken: googleAuth.accessToken,
),
);
return _userFromFirebase(authResult.user);
} else {
throw PlatformException(
code: 'ERROR_MISSING_GOOGLE_AUTH_TOKEN',
message: 'Missing Google Auth Token',
);
}
} else {
throw PlatformException(
code: 'ERROR_ABORTED_BY_USER',
message: 'Sign in aborted by user',
);
}
}
@override
Future<void> signOut() async {
final googleSignIn = GoogleSignIn();
await googleSignIn.signOut();
final facebookLogin = FacebookLogin();
await facebookLogin.logOut();
await _firebaseAuth.signOut();
}
}
Call for Auth() methods
import 'dart:async';
import 'package:basics_for_darsh/authentication/signin.dart';
import 'package:basics_for_darsh/screens/welcome_screen.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'auth.dart';
class LandingPage extends StatelessWidget {
static const String id = 'landing_page';
@override
Widget build(BuildContext context) {
final auth = Provider.of<AuthBase>(context);
return StreamBuilder<MyUser>(
stream: auth.onAuthStateChanged,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
MyUser user = snapshot.data;
if (user == null) {
return AppSignIn();
}
return WelcomeScreen();
} else {
return Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
});
}
}
initializeApp()
is asynchronous, therefore do the following:
Auth(){
_intializeMe().then((_){
_firebaseAuth = FirebaseAuth.instance;
});
}
Future<void> _intializeMe() async {
return await Firebase.initializeApp();
}
Before accessing FirebaseAuth, you have to initialize Firebase. Therefore you can use then()
which will register a callback that will be called when the future is done.