Initializing Firebase Throws an Error - Flutter - firebase

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

Related

flutterfire crashlytics not enable

not enable crashlyrics in firebase console, after
await Firebase.initializeApp();
FirebaseCrashlytics.instance.crash();
my code
Future<void> main() async {
//runZonedGuarded<Future<void>>(() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
FirebaseCrashlytics.instance.crash();//this i also set in initState and build
runApp(const MyApp());
//}, (error, stack) => FirebaseCrashlytics.instance.recordError(error, stack));
}
app/build.gradle:
implementation platform('com.google.firebase:firebase-bom:29.0.4')
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.google.firebase:firebase-analytics-ktx'
implementation 'com.google.firebase:firebase-crashlytics-ktx'
android/build.gradle:
classpath 'com.google.gms:google-services:4.3.10'
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1'
Tried start app with flutter run --release
also I tried use this example with my options: DefaultFirebaseOptions.currentPlatform: https://github.com/FirebaseExtended/flutterfire/blob/master/packages/firebase_crashlytics/firebase_crashlytics/example/lib/main.dart
I did everything according to the instructions from here https://firebase.flutter.dev/docs/ Getting started and Craslytics
don't have any errors, except for crashlytics not working in the firebase console
The problem was solved by another device, with android 11, with it there was a log about the request for crashlytics
There was no request on my device with 12 android, so far I will put the issue resolved, although I would like to have a solution to the problem for 12 android

Flutter Firebase notification is not displayed in onMessageOpenedApp and onBackgroundMessage

I have an application Flutter and I use firebase messaging. On most smartphones the message is received normally in all states (onMessage, onMessageOpenedApp, onBackgroundMessage). But on some smartphones, notification doesn't come (onMessageOpenedApp, onBackgroundMessage), I've tried some tips and it didn't work for me. My last attempt was this, top-level function :
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
print(
"Background message: ${message.notification.title}, ${message.notification.body}");
}
void main() {
FirebaseMessaging.onMessageOpenedApp.listen(_firebaseMessagingBackgroundHandler);
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(InitApp());
}
I'm using:
firebase_core : ^1.6.0
firebase_messaging : ^10.0.6
Please I need tips on what else I can try to do.

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.

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

Is there any way to load image from Firebase to flutter project according to current user UID

I want to load a image from my Firebase storage. I uploaded images such as profile photos for users with the name {users uid}.png. So when I go to users profile screen, I want to upload these images from firebase accordingly to the current user uid. What is the best way for that ?? I have a async method that sets my user properties such as final loggegInUser and I have a async method
void getCurrentUser() async {
try {
final user = await _auth.currentUser();
if (user != null) {
loggedInUser = user;
print(loggedInUser.email);
print(uid);
}
} catch (e) {
print(e);
}
}
This method sets my global loggedInUser property then I want to load the image from firebase storage like that
CircleAvatar(
backgroundColor: Colors.black,
backgroundImage: FirebaseImage(
'gs://homeparty-68792.appspot.com/user_profile_images/${loggedInUser.uid}.png')
,
radius: 100,
),
But when I load this screen I get
ERROR TYPE Exception has occurred. NoSuchMethodError (NoSuchMethodError: The getter 'uid' was called on null. Receiver: null Tried calling: uid)
error. getCurrentUser() methods work properly it prints the e mail and password but in the build Widget It returns null. Why this is happening I need some help ???
If you are calling getCurrentUser() in initState, then the problem is that the build() is getting called before retrieving the user. Therefore the best thing to do is to upgrade cloud_firestore to version 0.14.0 and to add firebase_core : 0.5.0:
dependencies:
flutter:
sdk: flutter
firebase_core : ^0.5.0
firebase_auth : ^0.18.0
firebase_storage:^4.0.0
# cloud_firestore: ^0.14.0 not sure if you are using
Then you can do the following, first initialize Firebase:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
and inside getCurrentUser():
void getCurrentUser() {
try {
final user = _auth.currentUser;
if (user != null) {
loggedInUser = user;
print(loggedInUser.email);
print(uid);
}
} catch (e) {
print(e);
}
}
In the new version, getting the currentUser isn't asynchronous anymore doesnt require async/await.
Some useful links:
No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() in Flutter and Firebase
Undefined class 'FirebaseUser'
cloud_firestore 0.14.0 how to use the data method
The getter 'instance' isn't defined for the type 'Firestore'

Resources