Flutter + Firebase | java.lang.IllegalStateException: FirebaseApp with name [DEFAULT] doesn't exist - firebase

I am trying to complete a very simple exercise by connecting my basic Flutter app to Cloud Firestore (in Firebase).
I have followed the instructions with regards to setup. However, I am getting the following error.
E/MethodChannel#plugins.flutter.io/cloud_firestore(13217): Failed to handle method call
E/MethodChannel#plugins.flutter.io/cloud_firestore(13217): java.lang.IllegalStateException: FirebaseApp with name [DEFAULT] doesn't exist.
My flutter code:
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Playground',
home: Scaffold(
appBar: AppBar(
title: Text('Playground App'),
),
body: Column(children: <Widget>[
Text('Sup World?'),
StreamBuilder(
stream: Firestore.instance.collection('test').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return const Text('Loading....');
return Text('Loaded');
},
)
])));
}
}
Dependencies in the android\build.gradle file
dependencies {
classpath 'com.android.tools.build:gradle:3.3.1'
classpath 'com.google.gms:google-services:4.0.1'
}
Dependencies and new lines added in the android\app\build.gradle file
dependencies {
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.firebase:firebase-core:16.0.1'
}
apply plugin: 'com.google.gms.google-services'
Dependencies in the pubspec.yaml
dependencies:
flutter:
sdk: flutter
intl: 0.15.7
cloud_firestore: ^0.8.2
I've also downloaded and added the google-services.json file to the android\app folder.
In the Firestore db, I have a collection with id test containing one document.
Expected result:
The text "Loaded" should appear under the text "Sup World?"
However, I am getting the above error and it's showing the text "Loading".
Could someone help in getting this resolved please?

I had posted this on GitHub as well. Running flutter clean on the project and then running the app again fixed it for me.
The url to the GitHub issue.
https://github.com/flutter/flutter/issues/28003

I got this error when I updated to newer google-services.
Switched back to classpath 'com.google.gms:google-services:3.2.1' and it started working fine.

Related

flutter firebase MissingPluginException

I just added firebase to my flutter App, i followed all the steps correctly, but i'm getting an error when initializing the app
this is my code to initialize app
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: new ThemeData(
canvasColor: Colors.white,
),
home: PersistentTabsDemo(),
onGenerateRoute: route.controller,
);
}
}
this are the dependecies i added to pubsec.yaml
firebase_core: ^1.6.0
firebase_analytics: ^8.3.1
firebase_auth: ^3.1.0
cloud_firestore: ^2.5.1
and this is the error
Error: MissingPluginException(No implementation found for method Firebase#initializeCore on channel
plugins.flutter.io/firebase_core)
Edit: i tried removing async and await from my main class now i'm getting new error
No firebase App 'default' has been created - call Firebase.intializeApp()
Try
Flutter clean
Pub.get
If these two doesn't work
Something is missing in setup of Firebase flutter
If anyone else had the same issue as me
I've fixed the issue by creating another project and added the sh1 and sh256 to firebase
just follow this tuto it's really helpful https://www.youtube.com/watch?v=CpyALC8Zpxo
PS: when u add firebase to your flutter project don't run it on chrome debug you will get an error, run it on your emulator or smartphone
happy coding ^^

Flutter app error message: No Firebase App

I recently went back to a Flutter project I've not touched for a couple of months and updated a few bits and pieces. Now, when I run the app in my emulator, I get the message:
[core/no-app] No Firebase App '[DEFAULT]' has been created
I added this line of code to initialize it in the app: await Firebase.initializeApp();... but it now doesn't appear to connect to my Firebase, just an empty one that I presume it has created on the fly.
This was my original code, which according to this site is the correct way to initialize the app: https://firebase.flutter.dev/docs/overview/
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark(),
home: FutureBuilder(
future: _initialization,
builder: (context, snapshot) {...
Any idea what I'm doing wrong? The original app on my phone works fine with Firebase, so I presume it's something to do with updating Flutter, Firebase to the latest versions.
Thanks
You should initalize your app in the main function before you run your app, not in the MyApp widget.
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(); // add this line
runApp(MyApp());
}
Ah, it wasn't anything to do with the incorrect Firebase app. I did initialize it in the main function, but in debugging I found that it was hitting an error in reading an object from the database. It was just incorrectly defined. I fixed that and it works now.
Thanks

MissingPluginException(No implementation found for method Firebase#initializeCore on channel plugins.flutter.io/firebase_core) on release

I'm building an flutter app with Firebase auth. When I'm testing with flutter run at my android emulator or my android phone the app runs pretty well without major errors.
The problem happens when I try to build an apk or an appbundle and Firebase.initializeApp() fail.
Since I'm not running in debug mode I'm not sure how to trace this error.
[UPDATE]
I could trace the error catching the exception thrown from Firebase.initializeApp() and was MissingPluginException(No implementation found for method Firebase#initializeCore on channel plugins.flutter.io/firebase_core)
I still couldn't figured out why this error just appears on release while on debug runs perfectly.
Here is my app/build.gradle snippet
(...)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
(...)
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation platform('com.google.firebase:firebase-bom:26.2.0')
implementation 'com.google.firebase:firebase-dynamic-links'
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.google.firebase:firebase-auth'
implementation 'com.google.firebase:firebase-firestore'
}
And my project build.gradle dependecies
(...)
dependencies {
classpath 'com.android.tools.build:gradle:4.0.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.4'
classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.9, 0.99.99]'
}
(...)
And my firebase dependencies
dependencies:
flutter:
sdk: flutter
firebase_core: ^0.7.0
cloud_firestore: ^0.16.0
firebase_auth: ^0.20.0+1
firebase_storage: ^7.0.0
I was facing the same issue so what I did was in my main.dart file I just added this code and it worked out for me. What it does is if Firebase.intitalizeApp() fails then it will show an errorPage which i have created and if it loads then it can show the application home page and if it is still loading then it shows a loading page. Here is the code for it. Hope it helps you worked for me.
#override
Widget build(BuildContext context) {
return FutureBuilder(
// Initialize FlutterFire
future: Firebase.initializeApp(),
builder: (context, snapshot) {
// Check for errors
if (snapshot.hasError) {
return SomethingWentWrong();
}
// Show Application
if (snapshot.connectionState == ConnectionState.done) {
return StreamProvider<Help4YouUser>.value(
value: AuthService().user,
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: Wrapper(),
),
);
}
// Initialization
return PouringHourGlassPageLoad();
},
);
}

Are there negative consequences for calling Firebase initializeApp() twice?

While Firebase.initializeApp() only needs to be called once, are there negative consequences for calling it twice?
Background: I'm troubleshooting a [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() error and temporarily fixed it by adding await Firebase.initializeApp(); in void main() async in addition to my pre-existing final Future<FirebaseApp> _fbApp = Firebase.initializeApp();
Everything seems to work okay now. I intend to fix it, but if calling Firebase.initializeApp() twice isn't hurting anything, I can stick with my immediate priorities and move forward.
Here's the relevant block of code:
void main() async {
WidgetsFlutterBinding
.ensureInitialized(); // added per https://stackoverflow.com/questions/57689492/flutter-unhandled-exception-servicesbinding-defaultbinarymessenger-was-accesse
await Firebase
.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final Future<FirebaseApp> _fbApp = Firebase
.initializeApp(); // changed from "async { await Firebase.initializeApp();" per official "Getting started with Firebase on Flutter - Firecasts" video at https://youtu.be/EXp0gq9kGxI?t=920
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return StreamProvider<Userrr>.value(
value: AuthService().user,
// above specifies what stream we want to listen to and what data we expect to get back
child: MaterialApp(
Thanks!
UPDATE: I tried all the good advice below and nothing seemed to work. I think my code, an exact duplication from two tutorials (one for getting started with Firebase and another for Firebase auth 101) had one or more gaps because of package updates or other incompatibilities.
I went back to basics and wrote-out by hand and re-implemented every step for installing and setting-up Firebase Core from the official "FlutterFire Overview."
I re-read all the documentation, as suggested below.
I updated all packages, including firebase_auth: “^0.20.0" to firebase_auth: “^0.20.0+1" (the +1 change is to “FIX: package compatibility,” per the changelog).
And then finally, I created a backup of main.dart as old_main.dart, then copy-pasted the exact "Initializing FlutterFire" FurtureBuilder code, then carefully replaced each part of that generic code with my own. Here is each item I replaced:
// replaced "_initialization" with "_fbApp"
// replaced if (snapshot.hasError) ... "return SomethingWentWrong();" with the response from below
// replaced "return Loading();" with CircularProgressIndicator form below
// changed return MyAwesomeApp(); to return MyApp();
// changed "class App extends StatelessWidget" to "class MyApp extends StatelessWidget
// replaced "MyAwesomeApp();" from "if (snapshot.connectionState == ConnectionState.done) { return MyAwesomeApp();" with all the "StreamProvider<Userrr>.value(..." code EXCEPT changed home to "home: Wrapper(),"
It may seem elementary, but for a novice like myself, it was the only way forward. Thankfully it worked!
Here's the full working code excerpt:
void main() {
WidgetsFlutterBinding
.ensureInitialized(); // added by mgav, per https://stackoverflow.com/questions/57689492/flutter-unhandled-exception-servicesbinding-defaultbinarymessenger-was-accesse
// await Firebase.initializeApp(); // added by mgav to test, KNOWING the Firebase is already initialized as a future below in line 25. Was trying to test (temp?) fix for error: “[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() The relevant error-causing widget was: MyApp file:///Users/mgav/AndroidStudioProjects/brand_new_flutter_app/lib/main.dart:21:10”
runApp(MyApp());
}
// BEGIN Firebase FutureBuilder code pasted from docs at https://firebase.flutter.dev/docs/overview/#initializing-flutterfire (replaces next section of commented-out code)
class MyApp extends StatelessWidget {
// Create the initialization Future outside of `build`:
final Future<FirebaseApp> _fbApp = Firebase.initializeApp();
#override
Widget build(BuildContext context) {
return FutureBuilder(
// Initialize FlutterFire:
future: _fbApp,
builder: (context, snapshot) {
// Check for errors
if (snapshot.hasError) {
print('You have an error! ${snapshot.error.toString()}');
return Text('Something went wrong main.dart around line 48');
}
// Once complete, show your application
if (snapshot.connectionState == ConnectionState.done) {
return StreamProvider<Userrr>.value(
value: AuthService().user,
// above specifies what stream we want to listen to and what data we expect to get back
child: MaterialApp(
title: 'Real Revs and Q&A',
theme: ThemeData(
primarySwatch: Colors.blueGrey,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
routes: {
// '/welcome': (context) => WelcomeScreen(),
'/cleanwritereview': (context) => CleanWriteReviewScreen(),
'/registrationscreen': (context) => RegistrationScreen(),
'/loginscreen': (context) => LoginScreen(),
'/viewreviewsscreen': (context) => ViewReviewsScreen(),
'/homescreen': (context) => Home(),
},
home: Wrapper(),
),
);
}
// Otherwise, show something whilst waiting for initialization to complete
return Center(
child: CircularProgressIndicator(),
);
},
);
}
}
You'll get an error message if you call initializeApp() twice for the same FirebaseApp.
In your case, you can get the app that you've already created with:
final FirebaseApp _fbApp = Firebase.app();
Also see the documentation on FlutterFire, specifically initializing and using FirebaseApp.
To initialise firebase you either do:
main(){
await Firebase.initializeApp(); // don't run the app until firebase is initialized
runApp(MyApp());
}
Or use a FutureBuilder which ensure the future is resolved before running the code inside the builder function.
#override
Widget build(BuildContext context) {
final _fbApp = Firebase.initializeApp();
return FutureBuilder(
future: _fbApp,
builder: (context, snapshot) { // waits until _fbApp is resolved to execute.
....
});
}
You get an error because you don't await _fbApp future.
In your code there is no guarantee AuthService().user is executed after initializeApp has finished. To garantee this you have to wait until initializeApp() is resolved by using await, then or a FutureBuilder.
Add a try catch to understand why the first call in initializeApp is not working.
Firebase initialises its core services only once. there is exactly one FirebaseApp instance by name. When you don't specify the name '[DEFAULT]' is used.
Try doing this:
final app = await Firebase.initializeApp();
final app2 = await Firebase.initializeApp();
print(app == app2); // is true
Please provide more details on your setup:
firebase_auth, firebase_core versions,
Execution plateform (Android, ios or web).
In the last version of fire_auth we use:
FirebaseAuth.instance.authStateChanges // stream to subscribe to the user's current authentication state.

How to use Flutter (web app) stream builder with Firestore

I see several questions and answers about Flutter for mobile that use stream builder like this:
body: new StreamBuilder(
stream: Firestore.instance.collection("collection").snapshots(),
builder: (context, snapshot) {
...
I'm trying to do the same on flutter for the web, but in my configuration, the snapshots() method is unknown, generating an exception while running (and a vscode warning beforehand). Why? Do I have an incorrect setup?
I've followed these steps which I found here and elsewhere:
1) Included firebase as a dependency in pubspec.yaml
dependencies:
flutter:
sdk: flutter
firebase: ^6.0.0
2) Included the firestore js scripts in the index.html body tag:
<script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-firestore.js"></script>
<script src="main.dart.js" type="application/javascript"></script>
3) In main.dart, imported firebase.dart files (using advice given here, though I'm not exactly sure which step above got me access to this package. I'm a flutter nube, if it isn't obvious)
import 'package:flutter/material.dart';
import 'package:firebase/firebase.dart' as fb;
import 'package:firebase/firestore.dart' as fs;
Having followed these steps, I can get this code working....
void main() {
if (fb.apps.length == 0) {
try {
fb.initializeApp(
apiKey: "mike",
authDomain: "myauthdomain",
databaseURL: "mydburl",
projectId: "myproductid",
storageBucket: "mystoragebucket",
);
} catch(e) {
print(e);
}
}
fs.Firestore store = fb.firestore();
fs.CollectionReference ref = store.collection("MyCollection");
ref.onSnapshot.listen((querySnapshot) {
querySnapshot.docs.forEach((doc) {
print(doc.data()); // this works!!
});
});
runApp(MyApp());
}
But, as I mentioned earlier, getting the stream builder working, all of the advice suggests that I can get a stream of snapshots by saying...
class MyList extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new StreamBuilder(
stream: fb.firestore().collection('MyCollection').snapshots(),
...
The packages I have running on web don't seem to have anything like the snapshots method (or property) on a firestore collection reference. Can somebody set me straight?
I had the same issue when I tried to create a web version of my flutter mobile app which uses a lot of StreamBuilders. The following works for me:
Pubspec.yaml dependencies:
firebase_web: ^5.0.9
firebase_core: ^0.4.3+2
In your code:
import 'package:firebase_web/firestore.dart';
import 'package:firebase_web/firebase.dart';
body: new StreamBuilder(
stream: firestore().collection('collection').onSnapshot,
builder: (context, snapshot) {
...
Below I have included a list with changes that I encountered so far going from a flutter mobile app to a flutter web app:
documents = docs as in snapshot.data.docs.length
documents() = doc() as in firestore().collection('foo').doc('bar')
reference = ref as in snapshot.ref
data = data() as in snapshot.data()
The method setData from Firestore = set
The method updateData from Firestore = update(data:{'yourKey': 'yourValue',})
Hope this can help!
The querySnapshot.docs property returns a List<DocumentSnapshot>, while you need a stream for the stream property where each item on the stream is a list.
I've only needed this with the FlutterFire libraries for iOS/Android, but it should look something like this:
Stream<List<DocumentSnapshot>> getStream() async* {
fb.firestore().collection("MyCollection").onSnapshot.listen((querySnapshot) {
yield querySnapshot.docs;
}
}

Resources