not able to use firebase integration in flutter - firebase

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());
}

Related

Initializing FIrebase on Flutter throws error

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!

Facing 'No Firebase App has been created' while uploading to Firebase Storage in a Flutter app

I want to collect user browsing data for offline backend analysis for a Flutter app. What is the optimal way to do that?
What I am planning to do is run a daily cron on the app that uploads it using the WorkManager package.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
Workmanager().initialize(uploadUserData, isInDebugMode: true);
Workmanager()
.registerOneOffTask('1', 'task1', initialDelay: Duration(seconds: 10));
runApp(MyApp());
}
void uploadUserData() {
Workmanager().executeTask((task, inputData) {
firebase_storage.FirebaseStorage.instance
.ref('/uploads/test_workmanager.txt')
.putString('workmanager test');
return Future.value(true);
});
}
I am facing the following issue while running the above code
E/BackgroundWorker( 6733): errorCode: error, errorMessage: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
I/WM-WorkerWrapper( 6733): Worker result FAILURE for Work [ id=81642715-826f-4d40-b8ec-9d86eab75136, tags={ be.tramckrijte.workmanager.BackgroundWorker } ]
I have checked in multiple ways that firebase is initialized before calling the workmanager task (using firebase.apps.length & .whenComplete)
Update: Many are doubting whether firebase connection is right: basically everything just works if I just call firebase_storage....putString in the main() instead of within Workmanager().executeTask. So, the trouble is only due to Workmanager.
First call await Firebase.initializeApp(); in Workmanager().executeTask() async { }.
I recommend also "awaiting" all the following Firebase actions in the Workmanager task: await firebase_storage.FirebaseStorage.instance.[...]. This is because without await, the Workmanager might consider the task finished and kill the process before the Firebase action finishes.
Full Workmanager example task code with changes:
Workmanager().executeTask((task, inputData) async {
await Firebase.initializeApp();
await firebase_storage.FirebaseStorage.instance
.ref('/uploads/test_workmanager.txt')
.putString('workmanager test');
return Future.value(true);
});
You can call Firebase.initializeApp(); again in the Workmanager().executeTask() method before invoking any Firebase call.

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 :)

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());
}

Resources