Flutter FirebaseMessaging onBackgroundMessage Null check operator used on a null value - firebase

I'm building an app with firebase with push notifications so the app was running but after I used "flutter clean" this error appears without changing and piece of code
E/flutter (14812): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value
E/flutter (14812): #0 MethodChannelFirebaseMessaging.registerBackgroundMessageHandler (package:firebase_messaging_platform_interface/src/method_channel/method_channel_messaging.dart:180:53)
E/flutter (14812): #1 FirebaseMessagingPlatform.onBackgroundMessage= (package:firebase_messaging_platform_interface/src/platform_interface/platform_interface_messaging.dart:102:16)
E/flutter (14812): #2 FirebaseMessaging.onBackgroundMessage (package:firebase_messaging/src/messaging.dart:73:31)
E/flutter (14812): #3 main (package:mitaa/main.dart:37:21)
the error appears in the package firebase_messaging: ^11.2.6

https://firebase.flutter.dev/docs/messaging/usage/
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
await Firebase.initializeApp();
print("Handling a background message: ${message.messageId}");
}
void main() {
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(MyApp());
}
Blockquote

Related

Flutter Firebase has not been correctly initialized

I want to use firebase in my app,
I write this:
main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(Myapp());
}
but I got error :
I/ExoPlayerImpl( 5331): Init ba5fb7d [ExoPlayerLib/2.17.0] [generic_x86, Android SDK built for x86, unknown, 30]
E/flutter ( 5331): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [core/not-initialized] Firebase has not been correctly initialized.
E/flutter ( 5331):
E/flutter ( 5331): Usually this means you've attempted to use a Firebase service before calling `Firebase.initializeApp`.
E/flutter ( 5331):
E/flutter ( 5331): View the documentation for more information: https://firebase.flutter.dev/docs/overview#initialization
E/flutter ( 5331):
E/flutter ( 5331): #0 MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:99:9)
E/flutter ( 5331): <asynchronous suspension>
E/flutter ( 5331): #1 Firebase.initializeApp (package:firebase_core/src/firebase.dart:42:31)
and this:
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
how can I solve it?
can anyone help me, please?
Does it solve the issue if you replace the initializeApp() line with the following?
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);

FCM - A background message could not be handled in Dart as no onBackgroundMessage handler has been registered

I did exactly as mentions in the docs, a Future method outside of main() and onBackgroundMessage inside it
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async{
print("Handling a background message: ${message.messageId}");
}
main() async {
FirebaseMessaging.onBackgroundMessage((message){
return _firebaseMessagingBackgroundHandler(message);
});
}
but when I run the app I get error:
Unhandled Exception: Null check operator used on a null value
E/flutter (10760): #0 MethodChannelFirebaseMessaging.registerBackgroundMessageHandler (package:firebase_messaging_platform_interface/src/method_channel/method_channel_messaging.dart:180:53)
E/flutter (10760): #1 FirebaseMessagingPlatform.onBackgroundMessage= (package:firebase_messaging_platform_interface/src/platform_interface/platform_interface_messaging.dart:102:16)
E/flutter (10760): #2 FirebaseMessaging.onBackgroundMessage (package:firebase_messaging/src/messaging.dart:73:31)
E/flutter (10760): #3 main (package:neox/main.dart:56:21)
E/flutter (10760): #4 main (file:///E:/Flutter_Projects/NeoX/.dart_tool/flutter_build/generated_main.dart:102:42)
E/flutter (10760): #5 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:128:38)
E/flutter (10760): #6 _rootRun (dart:async/zone.dart:1426:13)
E/flutter (10760): #7 _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter (10760): #8 _runZoned (dart:async/zone.dart:1861:10)
E/flutter (10760): #9 runZonedGuarded (dart:async/zone.dart:1849:12)
E/flutter (10760): #10 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:126:5)
E/flutter (10760): #11 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
E/flutter (10760): #12 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
and when receiving a notification I get:
W/FLTFireMsgService(10760): A background message could not be handled in Dart as no onBackgroundMessage handler has been registered.
This is all the steps you need
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// you need to initialize firebase first
await Firebase.initializeApp();
print("Handling a background message: ${message.messageId}");
}
main() async {
WidgetsFlutterBinding.ensureInitialized();
// initialize firebase
await Firebase.initializeApp();
// you can just pass the function like this
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
}
I think you are misreading a Documentation
Here is how it should be in your main.dart
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
await Firebase.initializeApp();
print("Handling a background message: ${message.messageId}");
}
void main() {
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(MyApp());
}
And remember to config your AndroidManifest.xml
<service
android:name=".java.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
When you face this Error: java.lang.RuntimeException: Unable to create service rw.aos.im.java.MyFirebaseMessagingService: java.lang.ClassNotFoundException: Didn't find class "com.example.yourapp.java.MyFirebaseMessagingService"
Please use the following
<service
android:name="com.google.firebase.messaging.FirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Make sure that all of the following setups is configured correctly
https://firebase.google.com/docs/cloud-messaging/android/client
https://firebase.google.com/docs/android/setup
Hope this will solve your issue

Unhandled Exception: Null check operator used on a null value (Flutter FCM)

I am trying to implement notifications for my app, but when initializing notifications FirebaseMessaging.onBackgroundMessage((message) => myBackgroundMessageHandler(message))gives the following error. I have looked through this issue and this issue and have taken the function myBackgroundMessageHandler that I'm using as an argument outside the class but the error still persists.
Below is the error:
E/flutter (10115): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)]
Unhandled Exception: Null check operator used on a null value
E/flutter (10115): #0
MethodChannelFirebaseMessaging.registerBackgroundMessageHandler
(package:firebase_messaging_platform_interface/src/method_channel/method_channel_messaging.dart:179:53)
E/flutter (10115): #1
FirebaseMessagingPlatform.onBackgroundMessage=
(package:firebase_messaging_platform_interface/src/platform_interface/platform_interface_messaging.dart:101:16)
E/flutter (10115): #2 FirebaseMessaging.onBackgroundMessage
(package:firebase_messaging/src/messaging.dart:83:31) E/flutter
(10115): #3 main (package:okepos/main.dart:130:21) E/flutter
(10115):
Below is my code:
Future<dynamic> myBackgroundMessageHandler(RemoteMessage message) {
print('backgroundMessage: message => ${message.toString()}');
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage((message) => myBackgroundMessageHandler(message));
}
You might want to try and write your main function the following way. It might be that you need to initialize Firebase if you want to run your function in the background.
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
await Firebase.initializeApp();
print('Handling a background message ${message.messageId}');
if (message.notification != null) {
print(message.notification.title);
print(message.notification.body);
}
// Create a notification for this
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
// Background Message Handler
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(MyApp());
}
If you would like to see my implementation of Firebase Messaging with Flutter, check my github repo.

Firebase.initializeApp() gives error: Null check operator used on a null value

running this
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: ThePage(),
);
}
}
class ThePage extends StatelessWidget {
const ThePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
);
}
}
is giving Null check operator used on a null value and pointing out the line Firebase.initializeApp().
I have tried flutter clean too.
and the error in the stack trace
E/flutter (31894): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value
E/flutter (31894): #0 MethodChannel.binaryMessenger
package:flutter/…/services/platform_channel.dart:142
E/flutter (31894): #1 MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:148
E/flutter (31894): #2 MethodChannel.invokeMethod
package:flutter/…/services/platform_channel.dart:331
E/flutter (31894): #3 MethodChannel.invokeListMethod
package:flutter/…/services/platform_channel.dart:344
E/flutter (31894): #4 MethodChannelFirebase._initializeCore
package:firebase_core_platform_interface/…/method_channel/method_channel_firebase.dart:30
E/flutter (31894): #5 MethodChannelFirebase.initializeApp
package:firebase_core_platform_interface/…/method_channel/method_channel_firebase.dart:77
E/flutter (31894): #6 Firebase.initializeApp
package:firebase_core/src/firebase.dart:41
E/flutter (31894): #7 main
package:firebasetests/main.dart:5
E/flutter (31894): #8 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:142:25)
E/flutter (31894): #9 _rootRun (dart:async/zone.dart:1354:13)
E/flutter (31894): #10 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (31894): #11 _runZoned (dart:async/zone.dart:1789:10)
E/flutter (31894): #12 runZonedGuarded (dart:async/zone.dart:1777:12)
E/flutter (31894): #13 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:138:5)
E/flutter (31894): #14 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
E/flutter (31894): #15 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
This is the stack trace for the error, after removing Firebase.initializeApp() in the main it runs fine.
You should add the WidgetsFlutterBinding.ensureInitialized(); inside the main function:
void main() async {
WidgetsFlutterBinding.ensureInitialized(); // Add this
await Firebase.initializeApp();
runApp(MyApp());
}
For Firebase initialization, access to the native code is needed using Flutter Platform Channels. For this, you need to ensure that Flutter engine binding is initialized.
Use line of code which #mkobuolys mentioned.
I had same problem in Visual Studio Code but it didn't shows me any detailed information about error but Android Studio did.
Here is the most important information from the exception message if anyone is interested:
If you're running an application and need to access the binary
messenger before runApp() has been called (for example, during
plugin initialization), then you need to explicitly call the
WidgetsFlutterBinding.ensureInitialized() first. If you're running a
test, you can call the TestWidgetsFlutterBinding.ensureInitialized()
as the first line in your test's main() method to initialize the
binding.
add this line in android/app/build.gradle, this is worked for me
apply plugin: 'com.google.gms.google-services'

NoSuchMethodError: The method 'ref' was called on null

there I want help, I was creating my app with flutter and firebase,
there, I want to upload images to firebase storage.
so my file
import 'package:firebase_storage/firebase_storage.dart';
uploadTOFirebase() async {
final ref = FirebaseStorage.instance.ref('posts/post_$postId.jpg');
await ref.putFile(image).whenComplete(() async {
final url = await ref.getDownloadURL();
setState(() {
postlink = url;
});
// print(postlink);
});
}
but that saw me that error
E/flutter (19469): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: NoSuchMethodError: The method 'ref' was called on null.
E/flutter (19469): Receiver: null
E/flutter (19469): Tried calling: ref("posts/post_27cfad88-62bb-4211-9e5b-0c6d1e9029be.jpg")
E/flutter (19469): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter (19469): #1 _UploadState.uploadTOFirebase (package:instaclone/pages/upload.dart:230:48)
E/flutter (19469): #2 _UploadState.HandleSubmit (package:instaclone/pages/upload.dart:226:11)
E/flutter (19469): <asynchronous suspension>
E/flutter (19469):
and I'm using flutter in andoird
Try using it like this.
final ref = FirebaseStorage.instance.ref().child("posts/post_$postId.jpg");
Did you call Firebase.initializeApp() anywhere? Without that, the Firebase SDKs won't be able to find your project on Google's servers.
See initializing FlutterFire in the FlutterFire docs for an example of how to do this.
uploadTOFirebase() async {
UploadTask storageUploadTask = FirebaseStorage.instance.putFile('posts/post_$postId.jpg');
TaskSnapshot storageTaskSnapshot =
await storageUploadTask.whenComplete(() => null);
String url = await storageTaskSnapshot.ref.getDownloadURL();
setState((){postlink = url;});
}
Try this code. Did some small changes.

Resources