0

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(),
              ),
            );
          }
        });
  }
}
mohit sharma
  • 89
  • 2
  • 10
  • I am trying to create a separate Authentication class that has various types of authentications as functions like signInAnonymously() and onAuthStateChanged(). The aim is to manage them in one place and use them via providers, there are no UI components in this class and it is purely a Dart class. Unfortunately every compile results in same error: No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp(). I have tried to initialize it in a constructor, assign it to a variable outside the constructor, etc but the error won't go away and I can not use _firebaseAuth. – mohit sharma Sep 27 '20 at 00:02
  • Please don't add additional information to comments. Instead: click the edit link under your question to add such information to the question itself. – Frank van Puffelen Sep 27 '20 at 00:30
  • Aside from that: the stack trace of the error message will show you where in your code you're calling – Frank van Puffelen Sep 27 '20 at 00:31
  • Where are you calling `Auth()`? – Subhendu Kundu Sep 27 '20 at 01:25
  • @FrankvanPuffelen The information in the comment is just rephrased information, trying to explain the same thing again, I can not put in main description coz it keeps merging it with https://stackoverflow.com/questions/63492211/no-firebase-app-default-has-been-created-call-firebase-initializeapp-in. – mohit sharma Sep 27 '20 at 06:01
  • @SubhenduKundu Updated information with StackTrace and the call for Auth() – mohit sharma Sep 27 '20 at 06:05
  • why dont u call initializeApp in main? – Peter Haddad Sep 27 '20 at 06:29
  • I get the following error when i call this initialization on a parent page like main() ' The following NoSuchMethodError was thrown building LandingPage(dirty, dependencies: [InheritedProvider]): The method 'authStateChanges' was called on null. Receiver: null Tried calling: authStateChanges()' – mohit sharma Sep 27 '20 at 07:04
  • @PeterHaddad I get the following error when i call this initialization on a parent page like main() ~ ```The following NoSuchMethodError was thrown building LandingPage(dirty, dependencies: [InheritedProvider]): The method 'authStateChanges' was called on null. Receiver: null Tried calling: authStateChanges()``` – mohit sharma Sep 27 '20 at 07:12
  • Try implementing the way FlutterFire does it with `setState()` then gradually build up to what you are trying to accomplish. Insert many `asserts()` whenever there is doubt about the value of something. – mLstudent33 Nov 23 '21 at 21:55

1 Answers1

2

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.

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
  • it gives me another error that the method was called on NULL as if it did not wait for it to be intialize. The following NoSuchMethodError was thrown building LandingPage(dirty, dependencies: [InheritedProvider]): The method 'authStateChanges' was called on null. Receiver: null Tried calling: authStateChanges() – mohit sharma Sep 27 '20 at 06:53
  • What should that callback do? – mLstudent33 Nov 23 '21 at 21:09
  • 1
    `initializeMe` returns a `Future`, therefore you can use `then()` method which takes a callback.. When `initializeMe` returns, the callback will be called. And the code where you set `_firebaseAuth` will be called @mLstudent33 – Peter Haddad Nov 23 '21 at 21:39
  • I already call `await Firebase.initializeApp();` in an async method called in `initState()` of the top level app and have Riverpod providers for the auth part and able to log in on mobile. On web, still getting `FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).` I went through all the steps here: https://firebase.flutter.dev/docs/installation/web/ – mLstudent33 Nov 23 '21 at 21:51
  • I was missing: `// Initialize Firebase firebase.initializeApp(firebaseConfig);` from web index.html https://firebase.flutter.dev/docs/installation/web/ – mLstudent33 Nov 23 '21 at 22:02