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!!
},
);
Related
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"]);
}
}
}
I installed firebase notification package in my Flutter project and setup the necessary settings for sending data.
Everything works fine on android, when the app is completely closed, when I send a parameter via firebase, the page I want opens, but on the ios part, when I click on the notification, it does not catch the click and the page I want does not open.
I would be very happy if you could help me where is the main point I should pay attention to for the ios part.
Main.dart
initialMessage = await FirebaseMessaging.instance.getInitialMessage();
if (initialMessage != null) {
if (initialMessage!.data['type'] == 'notification') {
await Future.delayed(const Duration(seconds: 4));
navigatorKey.currentState?.pushNamed(
'/notification'); // navigate to login, with null-aware check
}
}
pushNotificationService.dart
class PushNotificationService {
Future<void> setupInteractedMessage() async {
await Firebase.initializeApp();
RemoteMessage? initialMessage =
await FirebaseMessaging.instance.getInitialMessage();
if (initialMessage != null &&
initialMessage.data['type'] == 'notification') {
await Future.delayed(const Duration(seconds: 6));
navigatorKey.currentState?.pushNamed(
'/notification'); // navigate to login, with null-aware check
}
// Also handle any interaction when the app is in the background via a
// Stream listener
// This function is called when the app is in the background and user clicks on the notification
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
// Get.toNamed(NOTIFICATIOINS_ROUTE);
print(message.toMap().toString());
print(message.data['type'].toString());
if (message.data['type'] == 'notification') {
navigatorKey.currentState?.pushNamed('/notification');
}
});
await enableIOSNotifications();
await registerNotificationListeners();
}
registerNotificationListeners() async {
AndroidNotificationChannel channel = androidNotificationChannel();
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
var androidSettings =
const AndroidInitializationSettings('#mipmap/ic_launcher');
var iOSSettings = const IOSInitializationSettings(
requestSoundPermission: false,
requestBadgePermission: false,
requestAlertPermission: false,
);
var initSetttings =
InitializationSettings(android: androidSettings, iOS: iOSSettings);
flutterLocalNotificationsPlugin.initialize(initSetttings,
onSelectNotification: (message) async {
// This function handles the click in the notification when the app is in foreground
// Get.toNamed(NOTIFICATIOINS_ROUTE);
});
// onMessage is called when the app is in foreground and a notification is received
FirebaseMessaging.onMessage.listen((RemoteMessage? message) {
// Get.find<HomeController>().getNotificationsNumber();
print(message!.data['type'].toString());
print(message.toMap().toString());
if (message.data['type'] == 'notification') {
navigatorKey.currentState?.pushNamed('/notification');
}
RemoteNotification? notification = message.notification;
AndroidNotification? android = message.notification?.android;
// If `onMessage` is triggered with a notification, construct our own
// local notification to show to users using the created channel.
if (notification != null && android != null) {
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
icon: android.smallIcon,
playSound: true,
),
),
);
}
});
}
enableIOSNotifications() async {
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true, // Required to display a heads up notification
badge: true,
sound: true,
);
}
androidNotificationChannel() => const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
importance: Importance.max,
);
}
info.plist background modules
UIBackgroundModes
fetch
processing
remote-notification
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.
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.
Before switching to Flutter 2, I was using an old version of firebaseMessaging without problems, and now I have the latest version.After upgrading I get the following error:
The class 'FirebaseMessaging' doesn't have a default constructor.
And:
The method 'configure' isn't defined for the type 'FirebaseMessaging'.
Full class:
class ShowNotifications {
static final FirebaseMessaging firebaseMessaging = FirebaseMessaging();
static FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
new FlutterLocalNotificationsPlugin();
static void initialization(){
var initializationSettingsAndroid =
new AndroidInitializationSettings('#mipmap/ic_launcher');
var initializationSettingsIOS = new IOSInitializationSettings();
var initializationSettings = new InitializationSettings(
android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
}
static void showNotification(String title, String body) async {
await _demoNotification(title, body);
}
static Future<void> _demoNotification(String title, String body) async {
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'channel_ID', 'channel name', 'channel description',
importance: Importance.max,
playSound: true,
// sound: 'sound',
// sound: true,
showProgress: true,
priority: Priority.high,
ticker: 'test ticker');
var iOSChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics, iOS: iOSChannelSpecifics);
await flutterLocalNotificationsPlugin
.show(0, title, body, platformChannelSpecifics, payload: 'test');
}
static Future onSelectNotification(String payload) async {
showDialog(
// context: context,
builder: (_) {
return new AlertDialog(
title: Text("PayLoad"),
content: Text("Payload : $payload"),
);
},
);
}
static notification(){
firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
showNotification(message['notification']['title'], message['notification']['body']);
// print("onMessage: $message");
},
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
},
);
}
}
I was able to control this class from all the application pages.
What do I need to change with the new version. So that I can use the class as it was in the past.
Try to update your firebase_messaging package and also take care to use compatile packages for the other Firebase SDKs. I would recommend to copy the ones from the official documentation for each one you use.
Here is a full example how the new Firebase Messaging SDK would work with the new API:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../constants.dart';
FirebaseMessaging messaging = FirebaseMessaging.instance;
final _database = FirebaseDatabase.instance;
final _firestore = FirebaseFirestore.instance;
final _auth = FirebaseAuth.instance;
class MessagingService {
static bool showToast = true;
static String currentToken;
static void initialize() async {
await messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
if (message.notification != null) {
print('Message also contained a notification: ${message.notification}');
}
if (showToast && message.notification != null) {
Fluttertoast.showToast(
msg: "${message.notification.title}: ${message.notification.body} ",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
//backgroundColor: Colors.red,
//textColor: Colors.white,
fontSize: 16.0,
);
}
});
messaging.onTokenRefresh.listen((String token) async {
await syncToken();
});
await syncToken();
}
static Future<String> getToken() async {
String token = await messaging.getToken();
return token;
}
static Future syncToken() async {
try {
String token = await messaging.getToken();
if (token != currentToken) {
if (syncDatabase == databases.RealtimeDatabase) {
await _database
.reference()
.child(
'$kNotificationTokensSyncBasePath${_auth.currentUser.uid}/$token')
.set(true);
} else {
await _firestore
.doc('$kNotificationTokensSyncBasePath${_auth.currentUser.uid}')
.set({'$token': true}, SetOptions(merge: true));
}
currentToken = token;
}
} catch (e) {
print(e);
}
return;
}
static Future unsyncToken(User user) async {
try {
String token = await messaging.getToken();
if (syncDatabase == databases.RealtimeDatabase) {
await _database
.reference()
.child('$kNotificationTokensSyncBasePath${user.uid}/$token')
.set(null);
} else {
await _firestore
.doc('$kNotificationTokensSyncBasePath${_auth.currentUser.uid}')
.set({'$token': FieldValue.delete()}, SetOptions(merge: true));
}
currentToken = null;
} catch (e) {
print(e);
}
return;
}
}