How to get image notifications when we trigger notifications from postman? - flutter

I am integrating notifications into my applications. Initially, I used firebase I got image notifications in 3 states i.e., on foreground(Local Notifications) background, and terminated state. But when I trigger a notification from postman I am getting a notification for the foreground. But in the background and terminated state, I am getting plain notifications with no image. I am getting the image URL in the data.
import 'dart:convert';
import 'package:authentication/utils/shared_utils.dart';
import 'package:authentication/utils/utils.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import '../presentation/authentication/login/login_view.dart';
import 'package:authentication/utils/routes/routes.dart';
class NotificationHelper {
FirebaseMessaging messaging = FirebaseMessaging.instance;
String notificationText;
AndroidBitmap androidBitmap;
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
description:
'This channel is used for important notifications.', // description
importance: Importance.max,
playSound: true);
Future initializeFCM(String userId) async {
_initSettings(userId);
///handle messages when app is in foreground
_handleAndroidForegroundNotification();
_handleIosForegroundNotification();
///handle messages when app opened either from background or terminated state.
_onMessageOpened();
_onTerminated();
}
_initSettings(String userId) {
String uId = userId + "userSpecific";
messaging.subscribeToTopic("public");
messaging.subscribeToTopic(uId);
messaging.getToken().then((value) {
print("fcm token >>> " + value);
});
final AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('app_icon');
final IOSInitializationSettings initializationSettingsIOS =
IOSInitializationSettings(
requestBadgePermission: false,
requestAlertPermission: false,
onDidReceiveLocalNotification: _onDidReceiveLocalNotification,
);
final InitializationSettings initializationSettings =
InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsIOS,
macOS: null);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: _onSelectNotification);
}
Future<dynamic> _onSelectNotification(data) async {
debugPrint("OnSelect Message Log>>>>>>>.");
String userId = SharedUtils.getString('UserId');
if (userId.isEmpty && userId == "") {
SharedUtils.setString('route', data);
Navigator.push(Utils.navigatorKey.currentContext,
MaterialPageRoute(builder: (context) => LoginView()));
} else {
Navigator.of(Utils.navigatorKey.currentContext)
.push(Routes.generateRoute(data));
}
}
Future _onDidReceiveLocalNotification(
int id, String title, String body, String payload) async {
debugPrint("Did receive Message Log>>>>>>>.");
}
///handle foreground state for Android
Future _handleAndroidForegroundNotification() async {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
_showAndroidNotification(message);
});
}
///handle foreground state for iOS
Future _handleIosForegroundNotification() async {
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
}
///handle background state
Future _onMessageOpened() async {
FirebaseMessaging.onMessageOpenedApp.listen((message) {
debugPrint('onMessageOpenedApp clicked!>>>>>>>>>.');
final routeFromMessage = message.data["route"];
debugPrint('Route called for background***************');
String userId = SharedUtils.getString('UserId');
if (userId.isEmpty && userId == "") {
SharedUtils.setString('route', routeFromMessage);
Navigator.push(Utils.navigatorKey.currentContext,
MaterialPageRoute(builder: (context) => LoginView()));
} else {
Navigator.of(Utils.navigatorKey.currentContext, rootNavigator: true)
.push(Routes.generateRoute(routeFromMessage));
}
});
}
///handle terminated state
static _onTerminated() {
FirebaseMessaging.instance.getInitialMessage().then((message) {
if (message != null) {
final routeFromMessage = message.data["route"];
debugPrint('Route called for terminated state***************');
String userId = SharedUtils.getString('UserId');
if (userId.isEmpty && userId == "") {
SharedUtils.setString('route', routeFromMessage);
Navigator.push(Utils.navigatorKey.currentContext,
MaterialPageRoute(builder: (context) => LoginView()));
} else {
Navigator.of(Utils.navigatorKey.currentContext)
.push(Routes.generateRoute(routeFromMessage));
}
}
});
}
/// set data to the notification UI
Future _showAndroidNotification(RemoteMessage message) async {
RemoteNotification notification = message.notification;
AndroidNotification android = message.notification?.android;
if (notification != null && android != null) {
androidBitmap = null;
if (message.data['image'] != null && message.data['image'] != '') {
var imagesBytes = await Utils.getImageBytes(message.data['image']);
androidBitmap =
ByteArrayAndroidBitmap.fromBase64String(base64.encode(imagesBytes));
} else if (message.notification.android.imageUrl != null) {
var imagesBytes =
await Utils.getImageBytes(message.notification.android.imageUrl);
androidBitmap =
ByteArrayAndroidBitmap.fromBase64String(base64.encode(imagesBytes));
}
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
color: Colors.blue,
styleInformation: androidBitmap != null
? BigPictureStyleInformation(androidBitmap)
: null,
playSound: true,
icon: '#mipmap/ic_launcher',
),
),
payload: message.data["route"]);
}
}
}

Related

I am not getting image in push notifications when I triggered it from firebase

The below is the code for notification. Can anyone say what is the mistake or is there any code to add to get the image displayed in notification tray. I am using local notifications plugin to get the notifications. The below is the code for notification. Can anyone say what is the mistake or is there any code to add to get the image displayed in notification tray. I am using local notifications plugin to get the notifications.
class LocalNotificationService {
static var userId = SharedUtils.getString('UserId');
FirebaseMessaging messaging = FirebaseMessaging.instance;
static final FlutterLocalNotificationsPlugin _notificationsPlugin =
FlutterLocalNotificationsPlugin();
static getText() {
String title;
String body;
}
static void initialize(BuildContext context) {
final InitializationSettings initializationSettings =
InitializationSettings(
android: AndroidInitializationSettings("#mipmap/ic_launcher"),
iOS: IOSInitializationSettings(
requestSoundPermission: false,
requestBadgePermission: false,
requestAlertPermission: false));
_notificationsPlugin.initialize(initializationSettings,
onSelectNotification: (String route) async {
String userId = SharedUtils.getString('UserId');
if (userId.isEmpty && userId == "") {
SharedUtils.setString('route', route);
Navigator.push(
context, MaterialPageRoute(builder: (context) => LoginView()));
} else {
Navigator.of(Utils.navigatorKey.currentContext)
.push(Routes.generateRoute(route));
}
});
}
static Future initializeFCM(String userId) async {
String uId = userId + "userSpecific";
FirebaseMessaging.instance.subscribeToTopic("public");
FirebaseMessaging.instance.subscribeToTopic(uId);
print(">>>>>>> fcm started $uId");
FirebaseMessaging.instance.getToken().then((value) {
print("fcm token >>> " + value);
});
}
static void display(RemoteMessage message) async {
AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
//'This channel is used for important notifications.', // description
importance: Importance.high,
playSound: true);
try {
final id = DateTime.now().millisecondsSinceEpoch ~/ 1000;
final NotificationDetails notificationDetails = NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
//channel.description,
color: Colors.blue,
playSound: true,
icon: '#mipmap/ic_launcher',
));
await _notificationsPlugin.show(
id,
message.notification.title,
message.notification.body,
notificationDetails,
payload: message.data["route"],
);
} on Exception catch (e) {
debugPrint(e.toString());
}
}
static onForeground() {
Map notificationData;
FirebaseMessaging.onMessage.listen((message) {
// LocalNotificationService.initializeFCM(userId);
if (message.notification != null) {
notificationData = {
"title": message.notification.title,
"body": message.notification.body
};
}
LocalNotificationService.display(message);
});
return notificationData;
}
static onTerminated() {
FirebaseMessaging.instance.getInitialMessage().then((message) {
if (message != null) {
final routeFromMessage = message.data["route"];
debugPrint('Route called for terminated state***************');
String userId = SharedUtils.getString('UserId');
if (userId.isEmpty && userId == "") {
SharedUtils.setString('route', routeFromMessage);
Navigator.push(Utils.navigatorKey.currentContext,
MaterialPageRoute(builder: (context) => LoginView()));
} else {
Navigator.of(Utils.navigatorKey.currentContext)
.push(Routes.generateRoute(routeFromMessage));
}
}
});
}
static onMessageOpened() {
FirebaseMessaging.onMessageOpenedApp.listen((message) {
final routeFromMessage = message.data["route"];
print('Route called for background***************');
String userId = SharedUtils.getString('UserId');
Map notificationData = {
"title": message.notification.title,
"body": message.notification.body
};
if (userId.isEmpty && userId == "") {
SharedUtils.setString('route', routeFromMessage);
Navigator.push(Utils.navigatorKey.currentContext,
MaterialPageRoute(builder: (context) => LoginView()));
} else {
Navigator.of(Utils.navigatorKey.currentContext, rootNavigator: true)
.push(Routes.generateRoute(routeFromMessage));
}
return notificationData;
});
}
}

How to display notification in app in flutter

I'm trying to display the background and foreground notification in flutter using flutter_local_notifications package. here is my firebase class code
class FirebaseMessagingService {
final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
IOSInitializationSettings? _initializationSettingsIOS;
AndroidInitializationSettings? _initializationSettingsAndroid;
AndroidNotificationDetails? _androidLocalNotificationDetails;
AndroidNotificationChannel? androidNotificationchannel;
static FirebaseMessagingService? _messagingService;
NotificationDetails? _androidNotificationDetails;
InitializationSettings? _initializationSettings;
//NotificationNavigationClass _notificationNavigationClass = NotificationNavigationClass();
NotificationAppLaunchDetails? _notificationAppLaunchDetails;
bool? _didNotificationLaunchApp;
static FirebaseMessaging? _firebaseMessaging;
FirebaseMessagingService._createInstance();
factory FirebaseMessagingService() {
// factory with constructor, return some value
if (_messagingService == null) {
_messagingService = FirebaseMessagingService
._createInstance(); // This is executed only once, singleton object
_firebaseMessaging = _getMessagingService();
}
return _messagingService!;
}
static FirebaseMessaging _getMessagingService() {
return _firebaseMessaging ??= FirebaseMessaging.instance;
}
Future<String?> getToken() {
return _firebaseMessaging!.getToken();
}
Future initializeNotificationSettings() async
{
NotificationSettings? settings = await _firebaseMessaging
?.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
if (settings?.authorizationStatus == AuthorizationStatus.authorized) {
print('User granted permission');
} else
if (settings?.authorizationStatus == AuthorizationStatus.provisional) {
print('User granted provisional permission');
} else {
print('User declined or has not accepted permission');
}
androidNotificationchannel = const AndroidNotificationChannel(
NOTIFICATION_ID, // id
NOTIFICATION_TITLE, // title
description: NOTIFICATION_DESCRIPTION,
// description
importance: Importance.max,
);
//
await _flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(androidNotificationchannel!);
if (Platform.isIOS) {
//configure local notification for ios
await _initializeIosLocalNotificationSettings();
}
else {
//configure local notification for android
await _initializeAndroidLocalNotificationSettings();
}
}
Future<void> _initializeIosLocalNotificationSettings() async
{
_initializationSettingsIOS = const IOSInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false
);
_initializationSettings = InitializationSettings(
iOS: _initializationSettingsIOS
);
}
Future<void> _initializeAndroidLocalNotificationSettings() async
{
_initializationSettingsAndroid =
const AndroidInitializationSettings('mipmap/ic_launcher');
_initializationSettings = InitializationSettings(
android: _initializationSettingsAndroid,
);
_androidLocalNotificationDetails =
const AndroidNotificationDetails(
LOCAL_NOTIFICATION_ID,
LOCAL_NOTIFICATION_TITLE,
channelDescription: LOCAL_NOTIFICATION_DESCRIPTION,
importance: Importance.max,
priority: Priority.high);
_androidNotificationDetails =
NotificationDetails(android: _androidLocalNotificationDetails);
//This will execute when the app is open and in foreground
void foregroundNotification() {
try {
_showLocalNotification(localNotificationId: DateTime
.now()
.hour + DateTime
.now()
.minute + DateTime
.now()
.second,
notificationData: message?.data,
messageTitle:message?.notification?.title ,
messageBody: message?.notification?.body,
);
} catch (error) {
log("error");
}
});
}
void _showLocalNotification(
{int? localNotificationId, Map<String, dynamic>? notificationData,String? messageTitle,String? messageBody}) async
{
if (notificationData != null) {
log("Notification Data:${notificationData}");
await _flutterLocalNotificationsPlugin.show(
localNotificationId ?? 0, notificationData["title"]??messageTitle,
notificationData["body"]??messageBody,
_androidNotificationDetails,
payload: jsonEncode(notificationData));
}
}
//This will excute when the app is in background but not killed and tap on that notification
void backgroundTapNotification() {
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage? message) async {
try {
RemoteMessage? terminatedMessage = await _firebaseMessaging
?.getInitialMessage();
} catch (error) {
log("error");
}
});
}
}
and calling it in splash screen
#override
void initState() {
super.initState();
controller = AnimationController(
vsync: this, duration: const Duration(milliseconds: 500));
heartbeatAnimation =
Tween<double>(begin: 100.0, end: 250.0).animate(controller);
controller.forward().whenComplete(() {
controller.reverse();
});
void _setNotifications() async {
FirebaseMessagingService().foregroundNotification();
FirebaseMessagingService().backgroundTapNotification();
}
await FirebaseMessagingService().initializeNotificationSettings();
_setNotifications();
}
When i close the app and hit the API notification is displaying on background, but when i open the app and hit the API notification is not displaying, nor foreground and not on background.
please help me to get out from this problem.

Navigate to another screen when I click on Firebase push notification either in foreground or background in Flutter

I use Firebase messaging in my Flutter app , I want to navigate to another screen when I click on the notification even my app is in foreground or background , I used many functions and it doesn't trigger the click event and I can't find anything can solve my problem .
When I click on the notification when app is in foreground or background , nothing happened because it navigate to the same page .
And when I click on the notification when app is terminated , it opens on Splash screen and go to the home not the screen that I want .
I added this intent-filter in my Manifest
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
And I added this to the Json object
"click_action": "FLUTTER_NOTIFICATION_CLICK",
And here is how can I get background FCM in the 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((RemoteMessage? message) {
if (message != null) {
Navigator.push(context, MaterialPageRoute(builder: (context)=>DoneAndPaiedPagess(0)));
}
});
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;
}
}
In yaml
firebase_core: ^1.12.0
firebase_messaging: ^11.2.6
dependency_overrides:
firebase_messaging_platform_interface: 3.1.6
Edit : from multiple solutions , I tried the most common solution that I used onMessageOpenedApp in initState but it doesn't enter in it
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
Navigator.push(context, MaterialPageRoute(builder: (context)=>DoneAndPaiedPagess(0)));
});
In your code, you are using the flutter_local_notifications plugin and you are creating local notification when you get a push notification from firebase messaging.
Since the notification is not created by firebase messaging so, you are not getting on tap callback in getInitialMessage and onMessageOpenedApp.
In order to get on tap callback on local notifications, you can pass a callback function while initializing flutter_local_notifications
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
void selectNotification(String payload) async {
if (payload != null) {
debugPrint('notification payload: $payload');
// Here you can check notification payload and redirect user to the respective screen
await Navigator.push(
context,
MaterialPageRoute<void>(builder: (context) => SecondScreen(payload)),
);
}
}
For more, you can check flutter_local_notifications documentation
On your home widget within initState, check the getInitialMessage value :
// get the remote message when your app opened from push notification while in background state
RemoteMessage? initialMessage = await FirebaseMessaging.instance.getInitialMessage();
// check if it is exists
if (initialMessage != null) {
// check the data property within RemoteMessage and do navigate based on it
}
Check the firebase flutter documentation here https://firebase.flutter.dev/docs/messaging/notifications/#handling-interaction.
Use onMessageOpenedApp stream to listen when a notification is opened in the foreground or background. When the application is terminated, use getInitialMessage to get a pending notification.

Flutter firebase_messaging - flutter_local_notifications

when the app is opened (foreground) and I receive a notification I want to navigate to a screen. The other 2 cases are working fine (background & terminated). I'm using this example
https://pub.dev/packages/firebase_messaging/example
help please I'm stuck in this for 2 days now. I know that I should add payload on onMessage.listen ok but after I did this?!!
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
print('Handling a background message ${message.messageId}');
}
/// Create a [AndroidNotificationChannel] for heads up notifications
AndroidNotificationChannel channel;
/// Initialize the [FlutterLocalNotificationsPlugin] package.
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
FirebaseMessaging.instance.getToken().then((value) {
firebaseToken = value;
print('firebaseToken $firebaseToken');
});
if (!kIsWeb) {
channel = const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
'This channel is used for important notifications.', // description
importance: Importance.high,
);
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
}
runApp(MyApp());
}
'my home state'
int _messageCount = 0;
String constructFCMPayload(String token) {
_messageCount++;
return jsonEncode({
'token': token,
'data': {
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'via': 'FlutterFire Cloud Messaging!!!',
'count': _messageCount.toString(),
},
'notification': {
'title': 'Hello FlutterFire!',
'body': 'This notification (#$_messageCount) was created via FCM!',
},
});
}
#override
void initState() {
super.initState();
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
RemoteNotification notification = message.notification;
AndroidNotification android = message.notification?.android;
if (notification != null && android != null && !kIsWeb) {
print(message.data);
print('onMessage method');
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channel.description,
icon: 'launcher_icon',
),
),
);
}
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async {
print('A new onMessageOpenedApp event was published!');
print(message.data);
print('onMessageOpenedApp method');
if (loginState && message != null) {
if (message.data['module'] == 'article') {
articleID = await message.data['id'];
Navigator.pushNamed(context, 'ArticleDetails',
arguments: MessageArguments(message, true));
} else if (message.data['module'] == 'question') {
questionID = await message.data['id'];
Navigator.pushNamed(context, 'QuestionDetails',
arguments: MessageArguments(message, true));
} else if (message.data['module'] == 'reservation') {
Navigator.pushNamed(context, 'Reservations',
arguments: MessageArguments(message, true));
} else if (message.data['module'] == 'job') {
Navigator.pushNamed(context, 'Jobs',
arguments: MessageArguments(message, true));
} else if (message.data['module'] == 'addresses') {
Navigator.pushNamed(context, 'InterestedAddresses',
arguments: MessageArguments(message, true));
}
} else {
Splash();
}
});
FirebaseMessaging.instance
.getInitialMessage()
.then((RemoteMessage message) async {
if (loginState && message != null) {
if (message.data['module'] == 'article') {
articleID = await message.data['id'];
Navigator.pushNamed(context, 'ArticleDetails',
arguments: MessageArguments(message, true));
} else if (message.data['module'] == 'question') {
questionID = await message.data['id'];
Navigator.pushNamed(context, 'QuestionDetails',
arguments: MessageArguments(message, true));
} else if (message.data['module'] == 'reservation') {
Navigator.pushNamed(context, 'Reservations',
arguments: MessageArguments(message, true));
} else if (message.data['module'] == 'job') {
Navigator.pushNamed(context, 'Jobs',
arguments: MessageArguments(message, true));
} else if (message.data['module'] == 'addresses') {
Navigator.pushNamed(context, 'InterestedAddresses',
arguments: MessageArguments(message, true));
}
} else {
Splash();
}
});
}
When you display local notification from FCM message in Android, you have to configure a function that will handle this case: received message is tapped while Android app is in foreground.
So add this configuration where you initalize local notifications:
await _flutterLocalNotificationsPlugin!.initialize(
const InitializationSettings(
android: AndroidInitializationSettings(),
iOS: IOSInitializationSettings()),
onSelectNotification: _onSelectNotification);
And the function should look something like this:
Future<dynamic> _onSelectNotification(String? payload) async {
}
You can try to add you navigation inside onSelectNotification callback, which you can add on notification initialization
Like this:
// initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('app_icon');
final IOSInitializationSettings initializationSettingsIOS =
IOSInitializationSettings(
onDidReceiveLocalNotification: onDidReceiveLocalNotification);
final InitializationSettings initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: (){
// Set your navigation code here!!
},
);

Flutter onSelectNotification method doesn't show payload when app closed

I'm using flutterlocalnotifications package and FCM to send notifications to my users. Everything working perfectly. I can show notifications to my users when my app is in the background, foreground, or closed. I can reach payload value in foreground and background, but when the app is killed I can't reach payload anymore. I test in catlog but there isn't any print in the onSelectNotification.
How can reach this payload?
This is my notification handler class
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
'This channel is used for important notifications.', // description
importance: Importance.high,
);
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// await Firebase.initializeApp();
//Bildirim geldiği anda datayı elde ettiğimiz alan
final dynamic data = message.data;
print('Data in background : ${data.toString()}');
NotificationHandler.showNotification(data);
}
class NotificationHandler {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
static final NotificationHandler _singleton = NotificationHandler._internal();
factory NotificationHandler() {
return _singleton;
}
NotificationHandler._internal();
BuildContext myContext;
initializeFCMNotifications(BuildContext context) async {
await _firebaseMessaging.setForegroundNotificationPresentationOptions(
alert: true, badge: true, sound: true);
var initializationSettingsAndroid =
AndroidInitializationSettings('app_icon');
var initializationSettingsIOS = IOSInitializationSettings(
onDidReceiveLocalNotification: onDidReceiveLocalNotification);
var initializationSettings = InitializationSettings(
android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
await _firebaseMessaging.subscribeToTopic("all");
await FirebaseMessaging.instance
.getInitialMessage()
.then((RemoteMessage message) {
if (message != null) {
print('initialmessage tetiklendi : ' + message.data.toString());
}
});
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
var notification = message.notification;
var android = message.notification?.android;
print('ONMESSAGE ÇALIŞTI');
print('onmessage tetiklendi data : ' +
message.data['message'] +
' title ' +
message.data['title']);
showNotification(message.data);
});
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print('Onmessageopened : ' + message.data.toString());
});
}
static void showNotification(Map<String, dynamic> data) async {
const androidPlatformChannelSpecifics = AndroidNotificationDetails(
'1234', 'Yeni Mesaj', 'your channel description',
importance: Importance.max, priority: Priority.high, ticker: 'ticker');
const IOSPlatformChannelSpecifics = IOSNotificationDetails();
const platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
iOS: IOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0, data['title'], data['message'], platformChannelSpecifics,
payload: 'The value when notification tapped');
}
Future onSelectNotification(String payload) async {
if (payload != null) {
debugPrint('notification payload : $payload');
}
}
Future onDidReceiveLocalNotification(
int id, String title, String body, String payload) {}
}
and these are the versions of the packages I use
firebase_messaging: ^9.1.1
flutter_local_notifications: ^5.0.0+1