Search code examples
flutterfirebase-cloud-messagingflutter-dependenciesflutter-local-notification

Flutter - Firebase messaging - on onBackgroundMessage - Unhandled Exception: Null check operator used on a null value


I have made seperate PushNotificationService for all the notification service like bewlow

import 'package:dio/dio.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(
    RemoteMessage remoteMessage) async {
  await Firebase.initializeApp();
  await PushNotificationService.instance.initializeNotification();
  PushNotificationService.instance.showFlutterNotification(remoteMessage);
  debugPrint('Handling a background message ${remoteMessage.messageId}');
}

class PushNotificationService {
  PushNotificationService._privateConstructor();

  static final PushNotificationService instance =
      PushNotificationService._privateConstructor();
  String? fcmToken;
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();
  final String serverKey = "MyServerKey";
  late AndroidNotificationChannel channel;

  Future<void> initializeNotification() async {
    await Firebase.initializeApp();
    channel = const AndroidNotificationChannel(
        'high_importance_channel', // id
        'High Importance Notifications', // title
        description:
            'This channel is used for important notifications.', // description
        importance: Importance.high,
        enableVibration: true);
    await initializeLocalNotification();
    FirebaseMessaging firebaseMessaging = FirebaseMessaging.instance;
    fcmToken = await firebaseMessaging.getToken();
    debugPrint('FCM Token --> $fcmToken');

    NotificationSettings notificationSettings =
        await firebaseMessaging.requestPermission(
            announcement: true, alert: true, badge: true, sound: true);

    debugPrint(
        'Notification permission status : ${notificationSettings.authorizationStatus.name}');
    if (notificationSettings.authorizationStatus ==
        AuthorizationStatus.authorized) {
      FirebaseMessaging.onMessage.listen((RemoteMessage remoteMessage) async {
        debugPrint(
            'Message title: ${remoteMessage.notification!.title}, body: ${remoteMessage.notification!.body}');
        showFlutterNotification(remoteMessage);
      });
    }
    FirebaseMessaging.onBackgroundMessage(
        (message) => _firebaseMessagingBackgroundHandler(message));
  }

  Future<void> initializeLocalNotification() async {
    AndroidInitializationSettings android =
        const AndroidInitializationSettings('@mipmap/ic_launcher');
    DarwinInitializationSettings ios = const DarwinInitializationSettings();
    InitializationSettings platform =
        InitializationSettings(android: android, iOS: ios);
    await flutterLocalNotificationsPlugin.initialize(platform);
  }

  void showFlutterNotification(RemoteMessage message) {
    RemoteNotification? notification = message.notification;
    AndroidNotification? android = message.notification?.android;
    if (notification != null && android != null && !kIsWeb) {
      flutterLocalNotificationsPlugin.show(
        notification.hashCode,
        notification.title,
        notification.body,
        NotificationDetails(
          android: AndroidNotificationDetails(channel.id, channel.name,
              channelDescription: channel.description,
              icon: '@mipmap/ic_launcher',
              priority: Priority.high,
              importance: Importance.high),
        ),
      );
    }
  }

  Future<void> sendNotification(String fcmToken, String msg) async {
    Dio dio = Dio();
    dio.post(
      'https://fcm.googleapis.com/fcm/send',
      options: Options(
        headers: {
          "Content-Type": "application/json",
          "Authorization": "key=$serverKey"
        },
      ),
      data: {
        "to": fcmToken,
        "notification": {
          "title": "AppName",
          "body": msg,
        },
      },
    );
  }
}

Then I have called initializeNotification() function in main like below:

`Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  await MobileAds.instance.initialize();


  //push notification service
  await PushNotificationService.instance.initializeNotification();

  runApp(
    EasyDynamicThemeWidget(
      child: const MyApp(),
    ),
  );
}`

But I'm getting error below error:

E/flutter (13038): \[ERROR:flutter/runtime/dart_vm_initializer.cc(41)\] Unhandled Exception: Null check operator used on a null value
E/flutter (13038): #0      MethodChannelFirebaseMessaging.registerBackgroundMessageHandler (package:firebase_messaging_platform_interface/src/method_channel/method_channel_messaging.dart:201:53)
E/flutter (13038): #1      FirebaseMessagingPlatform.onBackgroundMessage= (package:firebase_messaging_platform_interface/src/platform_interface/platform_interface_messaging.dart:107:16)
E/flutter (13038): #2      FirebaseMessaging.onBackgroundMessage (package:firebase_messaging/src/messaging.dart:73:31)
E/flutter (13038): #3      PushNotificationService.initializeNotification (package:app_user/services/push_notification_service.dart:56:25)
E/flutter (13038): \<asynchronous suspension\>
E/flutter (13038): #4      main (package:app_user/main.dart:28:3)
E/flutter (13038): \<asynchronous suspension\>

I have used _firebaseMessagingBackgroundHandler function outside of the class still getting this error.

here is my flutter doctor

\[√\] Flutter (Channel stable, 3.10.6, on Microsoft Windows \[Version 10.0.19045.3324\], locale en-IN)
\[√\] Windows Version (Installed version of Windows is version 10 or higher)
\[√\] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
\[√\] Chrome - develop for the web
\[X\] Visual Studio - develop for Windows  
X Visual Studio not installed; this is necessary for Windows development.
Download at https://visualstudio.microsoft.com/downloads/.
Please install the "Desktop development with C++" workload, including all of its default components
\[√\] Android Studio (version 2021.3)
\[√\] Connected device (4 available)
\[√\] Network resources

package used: firebase_auth: ^4.7.3 firebase_core: ^2.15.1 firebase_messaging: ^14.6.7 flutter_local_notifications: ^15.1.1

Please help me out. Thank you


Solution

  • The flutter documentation for firebase states regarding the background function:

    It must not be an anonymous function.

    You are using an anonymous function. Try this instead:

    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);