Flutter local notifications - flutter

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());
}

Related

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 RepeatInterval local notification

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

(FLUTTER Android) flutter alarm manager not open app at the time when app is terminated

I'm make a flutter alarm app (with alarm_manager_plus).
When the app call
AndroidAlarmManager.oneShot(Duration(seconds:10),...);
On foreground, it wroks well, but when app is terminated (or mobile screen off) the app couldn't launch.
How could I deal with it?
https://pub.dev/packages/android_alarm_manager_plus/example
I tried this example.
in order to use app services in background you need to use this plugin
https://pub.dev/packages/flutter_background_service
example code
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await initializeService();
runApp(MyApp());
}
// this will be used as notification channel id
const notificationChannelId = 'my_foreground';
// this will be used for notification id, So you can update your custom notification with this id.
const notificationId = 888;
Future<void> initializeService() async {
final service = FlutterBackgroundService();
const AndroidNotificationChannel channel = AndroidNotificationChannel(
notificationChannelId, // id
'MY FOREGROUND SERVICE', // title
description:
'This channel is used for important notifications.', // description
importance: Importance.low, // importance must be at low or higher level
);
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
await service.configure(
androidConfiguration: AndroidConfiguration(
// this will be executed when app is in foreground or background in separated isolate
onStart: onStart,
// auto start service
autoStart: true,
isForegroundMode: true,
notificationChannelId: notificationChannelId, // this must match with notification channel you created above.
initialNotificationTitle: 'AWESOME SERVICE',
initialNotificationContent: 'Initializing',
foregroundServiceNotificationId: notificationId,
),
...

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,
),
);
}```

Flutter Firebase Cloud Messaging how to Auto Dismiss/Cancel a notification?

I have successfully managed to receive FCM messages(on my mobile) via the console as well as from my NodeJs server. But how may I send & receive an FCM message that will arrive at my phone, do some tasks and then auto Cancel/Dismiss by itself?
Is this possible in Flutter with FCM?
In Android we use to have public Notification.Builder setTimeoutAfter (long durationMs)
Its more for just pinging the client app... and retrieving some data from the Apps local storage. Since it can be done automatically i want to do it without troubling the user.
These are the steps to accomplish the following
receiving a notification without disturbing the user(silently without any Alert in the system tray)
let localNotification Pkg start the progress Notification
do a background task and when finished
cancel the notification via LocalNotifications Pkg
Make sure you have the following in your .yaml file... at the time of solving this I had the following versions:
firebase_messaging: ^11.1.0
firebase_core: ^1.10.0
flutter_local_notifications: ^9.1.
For the Local Notification Package lets make a class to use its services
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class LocalNotificationService {
static final FlutterLocalNotificationsPlugin _notificationsPlugin = FlutterLocalNotificationsPlugin();
static void initialize(BuildContext context) {
final InitializationSettings initializationSettings = InitializationSettings(
android: const AndroidInitializationSettings("#mipmap/your_icon"));
_notificationsPlugin.initialize(initializationSettings);
}
//=================================================
//==============this is the update notification
static Future<void> showProgressNotification() async {
const int maxProgress = 5;
for (int i = 0; i <= maxProgress; i++) {
await Future<void>.delayed(const Duration(seconds: 1), () async {
final AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails('progress channel', 'progress channel',
channelDescription: 'progress channel description',
channelShowBadge: false,
importance: Importance.max,
priority: Priority.high,
playSound: false,
showProgress: true,
maxProgress: maxProgress,
progress: i);
final NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await _notificationsPlugin.show(
0,//I use this id to cancel it from below method
'progress notification title',
'progress notification body',
platformChannelSpecifics,
payload: 'item x');
});
}
}
//=========================and this is for the ProgressNotification to be cancelled
static Future<void> cancelNotification() async {
await _notificationsPlugin.cancel(0);
}
}//end of class
Make your you initialize it in the init method of your Widget
#override
void initState() {
// TODO: implement initState
super.initState();
LocalNotificationService.initialize(context);
}
And lastly... this is how your Main() and top handler will look
//Receive message when app is in background/minimized
//THIS IS THE TOP LEVEL HANDLER.. as it is outside the scope of main()
Future<void> backgroundHandler(RemoteMessage message) async{
print("from the Background Handler Top Function()..............");
print(message.data.toString());
//now for the localNotification to take over
await LocalNotificationService.showProgressNotification();
await Future<void>.delayed(const Duration(seconds: 2));//faking task delay
await LocalNotificationService.cancelNotification();//by default I have made id=0
}
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(backgroundHandler);//this has to be a TOP LEVEL METHOD
runApp(MyApp());
}
And on the Server side while sending the notification make sure there is only data{}... see #Junsu Cho answer
ios is impossible
android is possible, remove notification payload
{
"to": "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
"notification":
{
"title": "title"
}
"data":
{
"data" : "data"
}
}
to
{
"to": "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
"data":
{
"data" : "data"
}
}