Flutter RepeatInterval local notification - flutter

anybody knows how to make the periodicaly show in flutter to show different notification and not the same over and over again?
Here is my code:
Future<void> showNotification(int id, String title, String body) async {
await flutterLocalNotificationsPlugin.periodicallyShow(
id,
title,
body,
RepeatInterval.everyMinute,
const NotificationDetails(
// Android details
android: AndroidNotificationDetails('main_channel', 'Main Channel',
channelDescription: "ashwin",
importance: Importance.max,
priority: Priority.max),
// iOS details
iOS: DarwinNotificationDetails(
sound: 'default.wav',
presentAlert: true,
presentBadge: true,
presentSound: true,
),
),
androidAllowWhileIdle:
true, // To show notification even when the app is closed
);
}
It works fine but it show me the same notification over and over again, I call this function in another class and in the body I have a randomName variable from a list, the problem it s not updating at every notification as i want and it display one random String again at every interval of time. I want to be updated every time the user get a notification.
String? randomName;
final random = new Random();
randomName = names[random.nextInt(names.length)];
onPressed: () {
setState(() {
showToast();
NotificationService().showNotification(
1,
'sada',
randomName!,
);
});
},
This 2 codes are from another class

Related

Problem in flutter local notification grouping

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.

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 local notifications

anybody knows how can I make the notifications to be showed in flutter daily but with different notifications every day? I'm struggling for few days how to figure it out how can I make that work.
Here is my code:
Future<void> showNotification(int id, String title, String body) async {
await flutterLocalNotificationsPlugin.periodicallyShow(
id,
title,
body,
RepeatInterval.everyMinute,
const NotificationDetails(
// Android details
android: AndroidNotificationDetails('main_channel', 'Main Channel',
channelDescription: "ashwin",
importance: Importance.max,
priority: Priority.max),
// iOS details
iOS: DarwinNotificationDetails(
sound: 'default.wav',
presentAlert: true,
presentBadge: true,
presentSound: true,
),
),
androidAllowWhileIdle:
true, // To show notification even when the app is closed
);
}
}
String? randomName;
final random = new Random();
randomName = names[random.nextInt(names.length)];
onPressed: () {
setState(() {
showToast();
NotificationService().showNotification(
1,
'$randomNames ${widget.userPost}',
randomName!,
);
});
},
Here i call the notifications, but the problem is not updating, it update only if i press the button again, but i don t want to press the button every time. I want to press the button just only one time and after the String to be updated to every single notification.

Flutter local notifications

I' m using Flutter local notification for my app with repeatInterval, it's working fine but i want notifications to be different from one to another, cause with this code i get the same string from list over and over again. How can i edit the code to get another string when user get a notification?
Future<void> showNotification(int id, String title, String body) async {
await flutterLocalNotificationsPlugin.periodicallyShow(
id,
title,
body,
RepeatInterval
.everyMinute,
const NotificationDetails(
// Android details
android: AndroidNotificationDetails('main_channel', 'Main Channel',
channelDescription: "ashwin",
importance: Importance.max,
priority: Priority.max),
// iOS details
iOS: DarwinNotificationDetails(
sound: 'default.wav',
presentAlert: true,
presentBadge: true,
presentSound: true,
),
),
androidAllowWhileIdle:
true, // To show notification even when the app is closed
);
}
Here is the code from another class NotificationService and i called it here:
onPressed: () {
setState(() {
showToast();
NotificationService().showNotification(
1,
'$randomNames${widget.userPost}',
randomName!,
);
});
},
The problem it s only updating when i press the button again, i want to be updated every time when the user get a notification. Anybody know how to do that?
String? randomName;
final random = new Random();
randomName = names[random.nextInt(names.length)];
This is where i randomized the list called names, this code and the one from above are from a diferent screen class called IntroPage
How can I solve this problem?
if you want to set different notif, which means you need the the system to execute the function. but since its repeated notif, and the message was static, consider to use Workmanger.
https://pub.dev/packages/workmanager
with this ,you can execute your function to generate random text as a notification.
#pragma('vm:entry-point')
void callbackDispatcher() {
Workmanager().executeTask((task, inputData) {
//you function here to generete random String
// then show local notificaton
showNotification(); // call local notificaiton
return Future.value(true);
});
}
void main() {
Workmanager().initialize(
callbackDispatcher, // The top level function, aka callbackDispatcher
isInDebugMode: true // If enabled it will post a notification whenever the task is running. Handy for debugging tasks
);
Workmanager().registerPeriodicTask("task-identifier", "simpleTask");
runApp(MyApp());
}

Flutter - Endless notification on a single pusher beams event

Describe the bug
I am using pusher beams to fire event from server and I use flutter local notification to show the notification when the event is received by app.
Sample code to reproduce the problem
I have called initPusherBeams() in my init state (please read to the end I am quite sure this issues is with flutter local notifications)
#override
void initState() {
super.initState();
_setAuthData().then((_) {
if (_user?.id != null) initPusherBeams();
});
// notification related
_notiInit();
_requestPermissions();
_configureDidReceiveLocalNotificationSubject();
_configureSelectNotificationSubject();
// ask for app rating
WidgetsBinding.instance.addPostFrameCallback((_) => _ratingDialog());
}
and then, ininitPusherBeams function, I have
initPusherBeams() async {
// Let's see our current interests
await PusherBeams.instance.setDeviceInterests([
// 'App.Models.User.${_user!.id}',
'debug-new'
]);
// This is not intented to use in web
if (!kIsWeb) {
await PusherBeams.instance.onMessageReceivedInTheForeground(_onMessageReceivedInTheForeground);
}
}
void _onMessageReceivedInTheForeground(Map<Object?, Object?> data) {
AndroidNotificationDetails androidPlatformChannelSpecifics = const AndroidNotificationDetails(
'channel',
'My App Name',
channelDescription: 'New user registered',
playSound: false,
styleInformation: DefaultStyleInformation(true, true),
);
const IOSNotificationDetails iOSPlatformChannelSpecifics = IOSNotificationDetails(presentSound: false);
NotificationDetails platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
iOS: iOSPlatformChannelSpecifics,
);
log(json.encode(data));
// flutterLocalNotificationsPlugin.show(
// 0,
// 'New user registered',
// data['body'].toString(),
// platformChannelSpecifics,
// payload: data['title'].toString(),
// );
}
If I comment out flutterLocalNotificationsPlugin.show, the event fire only once as you can see in below screenshot.
but if I uncomment showing notification part which is the following code
flutterLocalNotificationsPlugin.show(
0,
'New user registered',
data['body'].toString(),
platformChannelSpecifics,
payload: data['title'].toString(),
);
The event fire endlessly (like in the screenshot below) and the notification keep appearing for each event continuously.
How come showing notification became some kind of loop and how should I fix this. Thanks in advance.
I end up showing the notification with SnackBar while the app is in foreground. While the apps is in background, the pusher beams package handle the notification and send it to notification center. Here's my code
initPusherBeams() async {
// Let's see our current interests
await PusherBeams.instance.setDeviceInterests([
'App.Models.User.${_user!.id}',
'debug-new'
]);
// This is not intented to use in web
if (!kIsWeb) {
await PusherBeams.instance.onMessageReceivedInTheForeground(_onMessageReceivedInTheForeground);
}
}
void _onMessageReceivedInTheForeground(Map<Object?, Object?> data) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(correctFont(data['body'] as String)),
duration: const Duration(milliseconds: 3000),
backgroundColor: brandBrown,
),
);
}```