Problem in flutter local notification grouping - flutter

I'm using flutter_local_notification to rended the incoming chat notifications from FCM trying to group messsages from one conversation. The grouping working properly but on receiving a new notification from a different conversation, it overrides and dismiss the previous group.
showNotification({
required int id,
required AndroidNotificationChannel channel,
required String title,
required String body,
required Map<String, dynamic> payload,
}) async {
final androidNotificationDetails = AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
groupKey: channel.groupId,
importance: Importance.max,
priority: Priority.max,
icon: '#mipmap/launcher_icon',
);
final iosNotificationDetails = DarwinNotificationDetails(
presentAlert: true,
presentBadge: true,
presentSound: true,
threadIdentifier: channel.groupId, // Notifications with the same threadIdentifier grouped automatically
);
final notificationDetails = NotificationDetails(
android: androidNotificationDetails,
iOS: iosNotificationDetails,
);
_flutterLocalNotificationsPlugin.show(
id,
title,
body,
notificationDetails,
payload: jsonEncode(payload),
);
if (channel.groupId == null) {
return;
}
//* Grouping Messages
List<ActiveNotification> activeNotifications = await _flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()!
.getActiveNotifications();
if (!activeNotifications.any((element) => element.groupKey == channel.groupId)) {
return;
}
if (activeNotifications.isNotEmpty) {
// For Android Versions >= 7.0
List<String> lines = activeNotifications.map((e) => e.body.toString()).toList();
InboxStyleInformation inboxStyleInformation = InboxStyleInformation(
lines,
contentTitle: '${lines.length - 1} messages',
summaryText: "${payload["name"].trim()} (${lines.length - 1} messages)",
);
AndroidNotificationDetails androupGroupDetails = AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
groupKey: channel.groupId,
styleInformation: inboxStyleInformation,
setAsGroupSummary: true,
);
NotificationDetails groupDetails = NotificationDetails(android: androupGroupDetails);
await _flutterLocalNotificationsPlugin.show(0, "", "", groupDetails, payload: jsonEncode(payload));
}
}
}
I've tried to group the same conversation messages in one notification but later on, the group disappeared on receiving a new notification from another user.

Related

Flutter_local_notifications notificationResponse.payload is always empty string,

I'm trying to setup my mobile app, so that when a user gets a FCM message, when they click on it, I can use data within the message to route them to appropriate screen.
My FCM message looks like this:
const fcmMessage = {
notification: {
title: title,
body: message
},
data:{
type:'Chat',
Name: 'Mike',
body:'test'
},
android: {
notification: {
title:title,
body: message,
channel_id:'high_importance_channel'
}
},
token: msgToken,
};
then within my main() method, I am initializing the Flutter_Local_notifications as per the code snippet below.
The issue is when I click on the notification, the payload is always an empty string?
These are the code lines that perform this. Why is the NotificationResponse.payload empty string?
ultimately, I need access the "data" object in the FCM message.
void onDidReceiveNotificationResponse(NotificationResponse notificationResponse) async {
print(notificationResponse.payload);
}
Here is the full main() method.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
// Set the background messaging handler early on, as a named top-level function
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
if (!kIsWeb) {
channel = const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title/
importance: Importance.high,
);
}
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
var initializationSettingsAndroid =
AndroidInitializationSettings('#mipmap/ic_launcher');
var initializationSettingsIOs = DarwinInitializationSettings();
var initSettings = InitializationSettings(
android: initializationSettingsAndroid, iOS: initializationSettingsIOs);
void onDidReceiveNotificationResponse(NotificationResponse notificationResponse) async {
print(notificationResponse.payload);
}
await flutterLocalNotificationsPlugin.initialize(initSettings,onDidReceiveNotificationResponse: onDidReceiveNotificationResponse,);
/// Create an Android Notification Channel.
/// We use this channel in the `AndroidManifest.xml` file to override the
/// default FCM channel to enable heads up notifications.
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Got a message whilst in the foreground!');
print('Message data: ${message.data}');
if (message.notification != null) {
RemoteNotification? notification = message.notification;
AndroidNotification? android = message.notification?.android;
FlutterLocalNotificationsPlugin s = FlutterLocalNotificationsPlugin();
s.show(
notification.hashCode,
notification?.title,
notification?.body,
NotificationDetails(
android: AndroidNotificationDetails(channel.id, channel.name,
icon: 'launch_background',
channelDescription: channel.description,
importance: Importance.max,
priority: Priority.high,
ongoing: true,
styleInformation: BigTextStyleInformation('')),
),
);
}
});
runApp(MyApp());
}
UPDATE, found what I needed. In the LocalNotification show method, we can add the payload attribute and set it to whatever part of the message.
For my use case, I encode the message.data , and then in the didReceive method, I can decode back to JSON object and use as needed.
s.show(
payload: jsonEncode(message.data),
notification.hashCode,
notification?.title,
notification?.body,
NotificationDetails(
android: AndroidNotificationDetails(channel.id, channel.name,
icon: 'launch_background',
channelDescription: channel.description,
importance: Importance.max,
priority: Priority.high,
ongoing: true,
styleInformation: BigTextStyleInformation('')),
),
);

Flutter schedule local notification does not work

I am trying to create a notification at a certain time but it is not working. The code does not throw any error but no notification is displayed on the device.
I am using flutter_local_notifications
Code that generates the notification:
Future<void> showNotification(
int hour, int id, String title, String body) async {
await flutterLocalNotificationsPlugin.zonedSchedule(
id,
title,
body,
_convertTime(hour),
const NotificationDetails(
android: AndroidNotificationDetails('main_channel', 'Main Channel',
channelDescription: "ashwin",
importance: Importance.max,
priority: Priority.max),
iOS: IOSNotificationDetails(
sound: 'default.wav',
presentAlert: true,
presentBadge: true,
presentSound: true,
),
),
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
androidAllowWhileIdle: true,
);
}
_converTime function code:
TZDateTime _convertTime(int hour) {
final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
tz.TZDateTime scheduleDate =
tz.TZDateTime(tz.local, now.year, now.month, now.day, hour, 47);
return scheduleDate;
}
The result of the function is correct and is as follows: 2022-07-14 12:47:00.000Z
However, if instead of using this function, I change it to
Future<void> showNotification(
int hour, int id, String title, String body) async {
await flutterLocalNotificationsPlugin.zonedSchedule(
id,
title,
body,
// _convertTime(hour), // this does not work
tz.TZDateTime.now(tz.local).add(Duration(seconds: 1)), // this work
const NotificationDetails(
android: AndroidNotificationDetails('main_channel', 'Main Channel',
channelDescription: "ashwin",
importance: Importance.max,
priority: Priority.max),
// iOS details
iOS: IOSNotificationDetails(
sound: 'default.wav',
presentAlert: true,
presentBadge: true,
presentSound: true,
),
),
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
androidAllowWhileIdle: true,
);
}
I don't understand what could be happening.
I appreciate any help in advance.
try this one, remove some properties if you don't want them...
Future zonedScheduleNotification(String note, DateTime date, occ) async {
// tz.TZDateTime.parse(location, formattedString)
int id = math.Random().nextInt(10000);
log(date.toString());
log(tz.TZDateTime.parse(tz.getLocation("Asia/Kolkata"), date.toString())
.toString());
try {
await flutterLocalNotificationsPlugin.zonedSchedule(
id,
occ,
note,
tz.TZDateTime.parse(tz.getLocation("Asia/Kolkata"), date.toString()),
NotificationDetails(
android: AndroidNotificationDetails(
'your channel id', 'your channel name',
channelDescription: 'your channel description',
largeIcon: DrawableResourceAndroidBitmap("logo"),
icon: "ic_launcher",
playSound: true,
sound: RawResourceAndroidNotificationSound('bell_sound')),
),
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
return id;
} catch (e) {
log("Error at zonedScheduleNotification----------------------------$e");
if (e ==
"Invalid argument (scheduledDate): Must be a date in the future: Instance of 'TZDateTime'") {
Fluttertoast.showToast(msg: "Select future date");
}
return -1;
}
}
Try this again.
tz.TZDateTime _convertTime(int hour) {
final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
tz.TZDateTime scheduleDate =
tz.TZDateTime(tz.local, now.year, now.month, now.day, hour, 47);
return scheduleDate;
}

Error flutter NotificationDetails too many positional arguments

I'm using NotificationDetails to show local notifications in my app:
class NotificationApi {
static final _notifications = FlutterLocalNotificationsPlugin();
static final onNotifications = BehaviorSubject<String?>();
static Future _notificationDetails() async {
return NotificationDetails(
android: AndroidNotificationDetails(
'channel id',
'channel name',
'channel description', //here shows the error
importance: Importance.max,
),
iOS: IOSNotificationDetails(),
);
}
static Future init({bool initScheduled = false}) async {
final android = AndroidInitializationSettings('#mipmap/ic_launcher');
final iOS = IOSInitializationSettings();
final settings = InitializationSettings(android: android, iOS: iOS);
await _notifications.initialize(
settings,
OnSelectNotification: (payload) async {
onNotifications.add(payload);
},
);
}
static Future showNotification({
int id = 0,
String? title,
String? body,
String? payload,
}) async =>
_notifications.show(
id,
title,
body,
await _notificationDetails(),
payload: payload,
);
}
At the moment to implement the third argument in AndroidNotificationDetails(), it is marked as error:
Too many positional arguments: 2 expected, but 3 found.
Try removing the extra positional arguments, or specifying the name for named
arguments.dartextra_positional_arguments_could_be_named
And it shows when i clicked on the () of the method:
I am guiding myself with this tutorial. This code is displayed at minute 2:05
YouTube Video
Channel description is a named parameter, you need to type channelDescription:"Your description"
android: AndroidNotificationDetails(
'channel id',
'channel name',
channelDescription:"Your description",
importance: Importance.max,
),
More about constructors.

Sound and pop-up notifications do not work in flutter

I am using local_notifications plugin in my android flutter app. I do everything according to the documentation and the notifications work but without sound and pop-up windows. Importance and priority set to max. Maybe the reason is in some settings of my phone or its OS (MIUI Global 11.0.3, Android 9 PKQ1)?
Notification code:
FlutterLocalNotificationsPlugin notificationsPlugin =
FlutterLocalNotificationsPlugin();
Future<void> initNotificationPlugin() async {
const AndroidInitializationSettings androidSettings =
AndroidInitializationSettings('ic_launcher');
final IOSInitializationSettings iosSettings =
IOSInitializationSettings();
final initSettings =
InitializationSettings(android: androidSettings, iOS:
iosSettings);
await notificationsPlugin.initialize(initSettings);
}
void showNotification(String title, String body,
DateTime dateTime, int id) async {
var androidDetails = AndroidNotificationDetails(
'notificationChannel', 'channel', 'description',
importance: Importance.max,
priority: Priority.max,
playSound: true,
showWhen: false,
enableVibration: true);
var iosDetails = IOSNotificationDetails();
var details = NotificationDetails(android: androidDetails, iOS:
iosDetails);
await notificationsPlugin.zonedSchedule(
id,
title,
body,
timezone.TZDateTime.from(
dateTime, timezone.getLocation('Europe/Moscow')),
details,
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime);
}

Flutter local notification body not showing all notification text (flutter_local_notifications package)

I used flutter_local_notifications: ^0.7.1+3 in my Flutter app to push schedule notifications. All is well in this but the problem in my notification body is that it shows just one line of text, and I can't expand or stretch notification to show all the notification body text.
This is my try:
class NotificationUtil {
final notifications = FlutterLocalNotificationsPlugin();
final int checkOutNotifyId = 0;
NotificationUtil(BuildContext context) {
final settingsAndroid = AndroidInitializationSettings('ic_notify_icon');
final settingsIOS = IOSInitializationSettings(
onDidReceiveLocalNotification: (id, title, body, payload) =>
onSelectNotification(context));
notifications.initialize(
InitializationSettings(settingsAndroid, settingsIOS),
onSelectNotification: (context) async => onSelectNotification);
}
Future<void> showCheckOutNotify([int maximumCheckoutHours]) async {
await notifications.periodicallyShow(
checkOutNotifyId,
AttendanceConstants.SCHEDULE_NOTIFICATION_TITLE,
AttendanceConstants.SCHEDULE_NOTIFICATION_BODY +
'$maximumCheckoutHours Hour/s of your attendance',
RepeatInterval.Hourly,
_ongoing);
}
NotificationDetails get _ongoing {
final androidChannelSpecifics = AndroidNotificationDetails(
'your channel id',
'your channel name',
'your channel description',
importance: Importance.Max,
priority: Priority.High,
ongoing: true,
);
final iOSChannelSpecifics = IOSNotificationDetails();
return NotificationDetails(androidChannelSpecifics, iOSChannelSpecifics);
}
add [ BigTextStyleInformation('') ] in [ AndroidNotificationDetails() ]
NotificationDetails get _ongoing {
final androidChannelSpecifics = AndroidNotificationDetails(
'your channel id',
'your channel name',
'your channel description',
importance: Importance.Max,
priority: Priority.High,
ongoing: true,
styleInformation: BigTextStyleInformation(''),
);
If anybody is here for the package awesome_notifications, use:
notificationLayout: NotificationLayout.BigText,
inside notification content.