flutter – FirebaseMessaging.instance.getInitialMessage return null message when I click on notification

I use Firebase messaging in my Flutter app , when I click on the notification background , I want to go to another specific screen so FirebaseMessaging.instance.getInitialMessage() triggered but message returns null .

And for foreground notification I use onMessageOpenedApp when I click on the notification ,
onMessageOpenedApp doesn’t trigger .

Here is the object that the backend team use like this

{
 "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification":{
      "title":"Portugal vs. Denmark",
      "body":"great match!"
    }
}

and here is my code in main.dart

const AndroidNotificationChannel channel = AndroidNotificationChannel(
    'high_importance', // id
    'High Importance Notifications', // title
    importance: Importance.high,
    playSound: true);
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();


Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  SessionManager sessionManager = SessionManager();

  await Firebase.initializeApp();
  //final sound = 'sound.mp3';
  print('A bg message just showed up :  ${message.messageId}');

  final android = AndroidInitializationSettings('@mipmap/ic_launcher');
  final ios = IOSInitializationSettings(
    requestSoundPermission: false,
    requestBadgePermission: false,
    requestAlertPermission: false,);
  final settings = InitializationSettings(android: android,iOS: ios);
  flutterLocalNotificationsPlugin.initialize(settings,);
  if(message.data['title'].toString().toLowerCase()=="new request") {
    sessionManager.getBadge().then((badge) {
      if (badge != null) {
        int x = badge + 1;
        sessionManager.saveBadge(x);
        print("notification number is " + x.toString());
      }
      else {
        sessionManager.saveBadge(1);
      }
    });

  }

  flutterLocalNotificationsPlugin.show(
      message.data.hashCode,
      message.data['title'],
      message.data['body'],
      NotificationDetails(
        android: AndroidNotificationDetails(
          channel.id,
          channel.name,
          importance: Importance.high,
          priority: Priority.high,
         // sound: RawResourceAndroidNotificationSound(sound.split('.').first),
          playSound: true,
          icon: '@mipmap/ic_launcher',
        ),

      ));
  /*NotificationApi.showNotification(
      title: message.data['title'],
      body: message.data['body'],
      payload: "",
      id:  int.parse(channel.id));*/

}


Future<void>  main() async{
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
      AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);

  await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
    alert: true,
    badge: true,
    sound: true,

  );
  


  runApp(MyApps());
  // configLoading();

}


class MyApps extends StatefulWidget {
  const MyApps({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return MyApp();
  }
}


class MyApp extends State<MyApps> {
  static  ValueNotifier<int> strikeNotifier = ValueNotifier(0);

  Color _primaryColor =  Color(0xff0d8b75);


  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      builder: () => MaterialApp(
        debugShowCheckedModeBanner: false,
        home: SplashScreen(),
      ),
      designSize: const Size(1080, 2280),
    );
  }


  void showNotification(String title, String body) async {
    await _demoNotification(title, body);
  }

  Future<void> _demoNotification(String title, String body) async {
    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
        'channel_I', 'channel name',
        showProgress: true,
        priority: Priority.high,
        playSound: true,
        ticker: 'test ticker');

    var iOSChannelSpecifics = IOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
        android: androidPlatformChannelSpecifics, iOS: iOSChannelSpecifics);
    await flutterLocalNotificationsPlugin
        .show(0, title, body, platformChannelSpecifics, payload: 'test');
  }

  @override
  void initState() {
    super.initState();

    FirebaseMessaging.instance.getInitialMessage().then((message) {

      RemoteNotification notification = message!.notification!;
      AndroidNotification android = message.notification!.android!;
      if (notification != null && android != null) {
        Navigator.push(context, MaterialPageRoute(builder: (context)=>Register()));
      }
    });

    getToken().then((value) {
      if(value!=null) {
        AppConstants.firebaseToken = value;
      }
    });


    FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    new FlutterLocalNotificationsPlugin();
    var initializationSettingsAndroid =  AndroidInitializationSettings('@mipmap/ic_launcher');
    var initializationSettingsIOS =  IOSInitializationSettings();
    var initializationSettings =  InitializationSettings(android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
    flutterLocalNotificationsPlugin.initialize(initializationSettings,
      );



    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      var data = message.data;
      //  AndroidNotification? android = message.notification?.android;/


      if (data != null ) {
        if(data['title'].toString().toLowerCase()=="new request") {
          SessionManager sessionManager = SessionManager(context);
          sessionManager.getBadge().then((badge) {
            if (badge != null) {
              setState(() {
                int x = badge + 1;
                strikeNotifier.value = x;
                sessionManager.saveBadge(x);
              });
            }
            else {
              strikeNotifier.value = 1;
              sessionManager.saveBadge(1);
            }
          });
        }
        print("entered");
        flutterLocalNotificationsPlugin.show(
            data.hashCode,
            data['title'],
            data['body'],
            NotificationDetails(
              android: AndroidNotificationDetails(
                channel.id,
                channel.name,
                playSound: true,
                icon: '@mipmap/ic_launcher',
              ),
            ));

      }
    });
   FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
  Navigator.push(context, MaterialPageRoute(builder: (context)=>DoneAndPaiedPagess(0)));

});
   
  }

  Future<String?> getToken() async{
    String? token = await FirebaseMessaging.instance.getToken();
    print("token is "+token!);
    return token;

  }
}

Leave a Comment