Flutter app error message: No Firebase App - firebase

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

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 - Provider working for Web app but when I run on Android it breaks?

I am creating a cross platform flutter app and started developing on the Web version. I have used provider throughout to pass various pieces of data around my app and thus far it works well.
However, when I run my app on Android, the same provider I have used to pull data from Firestore doesn't register any values. When I run on web, I get 2 when I print the length of my list of values whereas on Android, I get 0.
I appreciate there isn't a great deal of information here, but i'm wondering if anyone else has experienced the same issue? And if so, how did you resolve it? Thanks.
UPDATE - added code
Here is how I access the stream from firestore:
class OurDatabase {
final CollectionReference customCollection =
FirebaseFirestore.instance.collection('myCollection');
Stream<List<CustomClass>> get customitems {
return customCollection.snapshots().map(
(QuerySnapshot querySnapshot) => querySnapshot.docs
.map(
(document) => CustomClass.fromFirestore(document),
)
.toList(),
);
}
Here is my main.dart:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(
MultiProvider(
providers: [
StreamProvider<List<CustomClass>>.value(
value: OurDatabase().customitems,
initialData: <CustomClass>[],
),
],
child: MaterialApp(theme: OurTheme().buildTheme(), home: OurHomePage()),
),
);
}
I then access the custom list here:
class OurHeadlineList extends StatelessWidget {
#override
Widget build(BuildContext context) {
final List<CustomClass> items =
Provider.of<List<CustomClass>>(context);
print(items .length);
return Container();
}
}
I have swapped out provider for a stream builder and that works - I guess the problem lies with provider?
Like I mentioned previously, when I run on Chrome, the provider works perfectly. But when I run on Android emulator, it doesn't pick up any of the values. I am able to log into firebase through both platforms which confuses me even more. Thoughts?

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.

Flutter - how to get current context?

I am using Firebase cloud messaging for notifications, and i want to show a dialog or snackbar once i receive a notification when i am inside the application, my problem is that i am initializing the firebase configuration at the top of my widget tree (Splash screen once the app is starting)
_fireBaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
dynamic data = message['data'];
................ // Adding a snackbar/alertdialog here doesn't work
},
);
obviously if i set a dialog or snackbar it won't show since i need the context of my current page, is there any way to get the current context?
I also tried putting it inside the build widget of my splash screen but still the dialog isn't showing once i am on another page.
#override
Widget build(BuildContext context) {
_fireBaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("onMessage: $message");
dynamic data = message['data'];
if (data['id'] == '1') {
newPro = true;
} else if (data['id'] == '2') {
print("THIS WORKS!!!");
showDialog(
context: context,
builder: (context) => AlertDialog(
content: ListTile(
title: Text("TEST"),
subtitle: Text("TEST"),
),
actions: <Widget>[
FlatButton(
child: Text("OK"),
onPressed: () => Navigator.pop(context),
)
],
));
}
},
);
I had the exact same issue, but I found a brilliant thread on GitHub. Basically, you can create a navigatorKey and pass that in to MaterialApp, and then use that navigatorKey to change route.
See how in this thread: https://github.com/brianegan/flutter_redux/issues/5#issuecomment-361215074
I ended up using Overlay support:
https://pub.dev/packages/overlay_support
It is basically called at the very beginning of my tree just like wrapping providers at the main.dart, it worked like a charm, nothing else worked at all!
Also here is a tutorial that helped me a lot:
https://medium.com/flutter-community/in-app-notifications-in-flutter-9c1e92ea10b3
Because it makes me uncomfortable to have the answer embedded in a link, here is the answer (credit to xqwzts on Github).
Use a GlobalKey you can access from anywhere to navigate:
Create the key:
final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();
Pass it to your App:
new MaterialApp(
title: 'MyApp',
onGenerateRoute: generateRoute,
navigatorKey: navigatorKey,
);
Push routes:
navigatorKey.currentState.pushNamed('/someRoute');
An elegant solution to this problem is to use GlobalKey. That'll let you find the current BuildContext and do things with it.
You make a file called eg. global.dart looking like this:
import 'package:flutter/material.dart';
class GlobalVariable {
static final GlobalKey<NavigatorState> navState = GlobalKey<NavigatorState>();
}
You use this in your main() and MaterialApp() like this:
import 'global.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'fcm.dart'; // My Firebase Cloud Messaging code
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'screens/welcome_screen.dart';
void main() {
print('Running main()');
WidgetsFlutterBinding.ensureInitialized();
Firebase.initializeApp();
initializeFcm('', GlobalVariable.navState); // Sending the global key when initializing Firebase Cloud Messaging
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: WelcomeScreen(),
navigatorKey: GlobalVariable.navState, // Putting the global key in the MaterialApp
);
}
}
Then, in the file that handles Firebase Cloud Messaging, which I've named fcm.dart, you'll be able to use the GlobalKey to find the current context and use it, for example like this:
import 'package:blackbox/global.dart';
import 'online_screens/game_hub_screen.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
void initializeFcm(String token, GlobalKey myGlobalKey) async {
print('Initializing Firebase Cloud Messaging...');
await Firebase.initializeApp();
FirebaseMessaging.onMessageOpenedApp.listen((remoteMsg) {
// Using the currentContext found with GlobalKey:
Navigator.push(GlobalVariable.navState.currentContext, MaterialPageRoute(builder: (context) {
return GameHubScreen();
}));
});
}
do the initializing inside a build method of your first widget in the tree ! which normally it called an App widget and it is StateLess StateFull widget and inside the build method you have access to the BuildContext

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