Initializing FIrebase on Flutter throws error - firebase

So I have been trying to initialize my firebase with my flutter app but it keeps throwing an error every time, the code has no problem since flutter builds the app fine but just not firebase.
So this is my code to initialize firebase;
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool _initialized = false;
bool _error = false;
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) {
return MaterialApp();
and this is the error I keep getting:
Error: Assertion failed:
file:///home/pete/snap/flutter/common/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.4.0/lib/src/fire
base_core_web.dart:271:11
options != null
"FirebaseOptions cannot be null when creating the default app."
at Object.throw_ [as throw] (http://localhost:35305/dart_sdk.js:5061:11)
at Object.assertFailed (http://localhost:35305/dart_sdk.js:4986:15)
at firebase_core_web.FirebaseCoreWeb.new.initializeApp
(http://localhost:35305/packages/firebase_core_web/firebase_core_web.dart.lib.js:243:42)
at initializeApp.next (<anonymous>)
at http://localhost:35305/dart_sdk.js:38640:33
at _RootZone.runUnary (http://localhost:35305/dart_sdk.js:38511:59)
at _FutureListener.thenAwait.handleValue (http://localhost:35305/dart_sdk.js:33713:29)
at handleValueCallback (http://localhost:35305/dart_sdk.js:34265:49)
at Function._propagateToListeners (http://localhost:35305/dart_sdk.js:34303:17)
at _Future.new.[_completeWithValue] (http://localhost:35305/dart_sdk.js:34151:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:35305/dart_sdk.js:34172:35)
at Object._microtaskLoop (http://localhost:35305/dart_sdk.js:38778:13)
at _startMicrotaskLoop (http://localhost:35305/dart_sdk.js:38784:13)
at http://localhost:35305/dart_sdk.js:34519:9

I fixed the issue by the following steps:
Run flutter channel stable
Run flutter upgrade
replace await Firebase.initializeApp() with await Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: "AIzaSyD1C8QaEAxv9QJIm2DDF9N3_b3UZv5o",
appId: "1:270790104828:web:1da6b11a4729a7d79729",
messagingSenderId: "2707901048",
projectId: "todo-app-firebase-ce8",
),
);
replace the values with what you copied to index.html file when initializing web app on firebase console and copying the script code from there.
Restart the app.
Worked for me!

The firebase_options file is missing from your import statement and options is missing from the Firebase.initializeApp method.
Import the firebase_core plugin and firebase_options files.
//lib/main.dart
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
Add options parameter to the Firebase.initializeApp method inside the main function.
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options:
DefaultFirebaseOptions.currentPlatform);
runApp(const MyApp());
}
Documentation for FlutterFire - initializing-flutterfire

I was facing this issue so I just used this command and it was fixed. please try once before doing anything else
$ flutter upgrade

UPDATED:
Dont waste time on configuring it by yourself, use this CLI https://firebase.flutter.dev/docs/overview/#using-the-flutterfire-cli
Following the steps will lead you to configure it for all the platforms. Its MAGIC!

Related

Initializing Firebase Throws an Error - Flutter

While I was trying to set up Firebase, I learned that I need to initialize Firebase after the last updates. But when I run:
Firebase.initializeApp();
I get an error saying:
_CastError (Null check operator used on a null value)
I tried to remove it, afterwords everything worked fine.
This is the code I am running:
Future<void> main() async {
await Firebase.initializeApp();
runApp(SignIn());
}
According to documents this is how you can initialize firebase in your app:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(); //Make sure you imported firebase_core
runApp(SignIn());
);
}
Happy Fluttering :)

not able to use firebase integration in flutter

I am using firebase in flutter application after updating the libraries to the latest version.
Below is the code which was previously used but now I am facing error
CODE
void main() {
FirebaseFirestore.instance.settings(timestampsInSnapshotsEnabled: true).then((_) {
print("Timestamps enabled in snapshots\n");
}, onError: (_) {
print("Error enabling timestamps in snapshots\n");
});
runApp(MyApp());
}
ERROR
error: The expression doesn't evaluate to a function, so it can't be invoked.
when I am implementing the above code I get the error, please help me to resolve this
Here's a code that should fix it.
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
You need to Initialize the Firebase instance before runApp(MyApp());
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
//Before running App During load time initialize firebase instance.
runApp(MyApp());
}

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

How to use firebase initialize with routings in Flutter

I need to initialize the Fiberbese app in a flutter routed environment
EX: I wanna use
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
and after the future has completed I need to direct to the initialRoute
initialRoute:<**Replace this with a string after future returns**>,
routes: {
MyHomePage.Id :(context) => MyHomePage(),
SoundTester.Id :(context) => SoundTester(),
GoogleMapSample.Id:(context) => GoogleMapSample()
},
Is there any way to do this? or this is impossible to do?
Initialise your app in main.dart at the main() method like this
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized(); // add this line
await Firebase.initializeApp(); // add this line
runApp(MyApp());
}

How to initialize firebase crashlytics in Flutter?

I have already implemented firebase crashlytics to my Flutter project through dependency in pubspec.yaml and also in Gradle files and able to see the crashlytics dashboard in the firebase console.
Now my question is how can I initialize crashlytics in main.dart file and how to write log and catch error or crash for a particular page(say Home page).
I have tried from this link: https://pub.dev/packages/firebase_crashlytics/example
main.dart
final _kShouldTestAsyncErrorOnInit = false;
// Toggle this for testing Crashlytics in your app locally.
final _kTestingCrashlytics = true;
main() {
WidgetsFlutterBinding.ensureInitialized();
runZonedGuarded(() {
runApp(MyApp());
}, (error, stackTrace) {
print('runZonedGuarded: Caught error in my root zone.');
FirebaseCrashlytics.instance.recordError(error, stackTrace);
});
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: "My App",
debugShowCheckedModeBanner: false,
home: MainPage(),
theme: ThemeData(
accentColor: Colors.blue
),
);
}
}
class MainPage extends StatefulWidget {
#override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
Future<void> _initializeFlutterFireFuture;
Future<void> _testAsyncErrorOnInit() async {
Future<void>.delayed(const Duration(seconds: 2), () {
final List<int> list = <int>[];
print(list[100]);
});
}
// Define an async function to initialize FlutterFire
Future<void> _initializeFlutterFire() async {
// Wait for Firebase to initialize
await Firebase.initializeApp();
if (_kTestingCrashlytics) {
// Force enable crashlytics collection enabled if we're testing it.
await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
} else {
// Else only enable it in non-debug builds.
// You could additionally extend this to allow users to opt-in.
await FirebaseCrashlytics.instance
.setCrashlyticsCollectionEnabled(!kDebugMode);
}
// Pass all uncaught errors to Crashlytics.
Function originalOnError = FlutterError.onError;
FlutterError.onError = (FlutterErrorDetails errorDetails) async {
await FirebaseCrashlytics.instance.recordFlutterError(errorDetails);
// Forward to original handler.
originalOnError(errorDetails);
};
if (_kShouldTestAsyncErrorOnInit) {
await _testAsyncErrorOnInit();
}
}
#override
void initState() {
super.initState();
_initializeFlutterFireFuture = _initializeFlutterFire();
Firebase.initializeApp().whenComplete(() {
print("completed");
setState(() {});
});
checkLoginStatus();
}
}
Is it correct or any otherway to initialize crashlytics in flutter?
If i have to check whether there is any crash in HomePage, then how can i get that crash from home page and will show it in firbase crashlytics?
Yes, your configuration of the crashlytics is ok.
If you are using Firebase Auth, you can add the following code in order to have the ability to track crashes specific to a user:
FirebaseAuth.instance.onAuthStateChanged.listen((firebaseUser) {
if (firebaseUser != null && firebaseUser?.email != null) {
Crashlytics.instance.setUserEmail(firebaseUser.email);
}
if (firebaseUser != null && firebaseUser?.uid != null) {
Crashlytics.instance.setUserIdentifier(firebaseUser.uid);
}
if (firebaseUser != null && firebaseUser?.displayName != null) {
Crashlytics.instance.setUserName(firebaseUser.displayName);
}
});
Also, don't forget to track specific exceptions in catch of the try-catch block like this:
try {
//some code here...
} catch (e, s) {
Crashlytics.instance.recordError(e, s, context: "an error occured: uid:$uid");
}

Resources