Flutter: FCM background notification large icon - flutter

I'm using firebase_messaging and flutter_local_notifications for notifications, and I was able to show a large icon in case of local(foreground) notifications, but I didn't seem to find a way to show the same large icon when the app is background.

handle background noti and show noti using local notification.
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

This code help you to receive a Notification and to use in your app :
void initMessaging() {
var androiInit = AndroidInitializationSettings(‘#mipmap/ic_launcher’);//for logo
var iosInit = IOSInitializationSettings();
var initSetting=InitializationSettings(android: androiInit,iOS:
iosInit);
fltNotification = FlutterLocalNotificationsPlugin();
fltNotification.initialize(initSetting);
var androidDetails =
AndroidNotificationDetails(‘1’, ‘channelName’, ‘channel
Description’);
var iosDetails = IOSNotificationDetails();
var generalNotificationDetails =
NotificationDetails(android: androidDetails, iOS: iosDetails);
FirebaseMessaging.onMessage.listen((RemoteMessage message) { RemoteNotification notification=message.notification;
AndroidNotification android=message.notification?.android;
if(notification!=null && android!=null){
fltNotification.show(
notification.hashCode, notification.title, notification.
body, generalNotificationDetails);
}
});
}
If you have any difficulty, please check this article : Flutter Push Notification Medium.
Thanks.

A better way to use largeIcon is using the image property in notification payload when you are sending the notification:
const payload = {
notification: {
title: 'title',
body: 'description',
image: 'large_icon_url',
sound : "default"
},
};

1- use flutter_local_notifications in backgroundMessageHandler to display the image
2- remove the "notification" in the payload and add your data in
"data:{
title: 'title',
body: 'description',
image: 'image',
}"

Related

How to handle notification action button clicks in background in Flutter using awesome_notifications?

I am using awesome notifications in Flutter to show local notifications. My plan is to have an action button in a notification, which changes some values in the shared preferences in the background (without opening the app) when pressed. Is this even possible to do?
I tried using onActionReceivedMethod-listener and getInitialNotificationAction-method in my main function after initializing awesome notifications:
AwesomeNotifications().setListeners(onActionReceivedMethod: (action) async{
print(action.body);
});
// OR
ReceivedAction? receivedAction = await AwesomeNotifications().getInitialNotificationAction(
removeFromActionEvents: false
);
if (receivedAction?.body != null){
print(receivedAction.body);
}
Both of them worked (separetly used) only when the app had already started, but they also gave this error:
Awesome Notifications: A background message could not be handled in Dart because there is no dart background handler registered. (BackgroundService:58)
But how I could get it working when the app is not opened? Can I create a backgroung handler without Firebase, or is there some other way to achieve this?
Here is my code, how I create the notification:
static Future<void> createSimpleNotification() async {
await AwesomeNotifications().createNotification(
content: NotificationContent(
id: 1,
channelKey: 'important_channel',
title: 'Title',
body: 'Test',
largeIcon: 'asset://assets/iconPhoto.png'),
actionButtons: [
NotificationActionButton(
key:'key',
label: 'label',
actionType: ActionType.SilentBackgroundAction)]
);
}
I found the answer from here: Cannot find AwesomeNotifications().actionStream
I implemented it like this:
#pragma("vm:entry-point")
Future<void> _onActionReceivedMethod(ReceivedAction action) async {
print('It works');
}
And it worked both when the app was in the background or in the foreground.

Flutter FCM shows empty notification when no notification data is sent and when app is in bg

I'm sending FCM notification from my cloud functions to my flutter app.
I don't want the FCM system to handle notification display when the app is in background or terminated. Hence, I'm sending the data to show in notification in the data key instead of the notification key.
Cloud Functions:
await admin.messaging().sendMulticast({
tokens: userFCMTokens,
data: {
title: "Notification title to display",
body: "Notification body to display",
},
android: {
notification: {
channelId: "some_channel_id",
},
},
});
On the client side (i.e. Flutter app) I'm receiving/handling the FCM messages and displaying them with the awesome_notifications plugin.
Flutter:
AwesomeNotifications().createNotification(
content: NotificationContent(
id: message.hashCode,
channelKey: message.notification?.android?.channelId,
title: message.data['title'],
body: message.data['body'],
bigPicture: message.data['imageUrl'],
wakeUpScreen: true,
notificationLayout: NotificationLayout.BigPicture,
),
actionButtons: (message.data['actions'] as List<Map>?)
?.map(
(e) => NotificationActionButton(
key: e['key'],
label: e['label'],
),
)
.toList(),
);
This setup works properly when the app is in foreground but when in background or terminated it shows 2 notification. One proper and one totally empty notification.
I don't want the FCM SDK system to handle the notification hence I'm using data instead of notification but then this problem arises.

How to make on click notification IOS works

i hope you're doing good. I'm trying to solve one problem: everything woks fine, the notifications works fine on iOS but when i try to execute a code ( showDialog ) for the notification it doesnt works. I'm using onSelectedNotification: function to execute something, in Android it works perfectly but in iOS it's just not opening. Follow the initState
FirebaseMessaging.onMessage.listen((RemoteMessage message) { RemoteNotification? notification=message.notification;
AndroidNotification? android=message.notification?.android;
if(notification!=null && android!=null){
fltNotification.show(
notification.hashCode, notification.title, notification.
body, generalNotificationDetails);
}
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {// I've tried to use the function here too but it not works
});
Follow the configs for HomePage:
var androiInit = AndroidInitializationSettings('#mipmap/ic_launcher');//for logo
var iosInit = IOSInitializationSettings();
IOSNotificationDetails(presentAlert: true, presentBadge: true, presentSound: true);
var initSetting=InitializationSettings(android: androiInit,iOS:
iosInit);
flutterLocalNotificationsPlugin.initialize(initSetting, onSelectNotification: onSelectNotification);
And i'm using this onSelectNotification on flutterlocalnotificationsplugin to run my function ( showDialog ) but in IOS it not works. What can i do? Am I missing something?

Flutter Local Notifications doesn't execute code with app terminated

I have an app that schedules alarms, which trigger flutter local notifications. When pressing one of the buttons on these notifications, the database gets updated to reflect that you've turned off the alarm.
However, when the app is terminated/closed down, it seems as if no code gets executed and the database doesn't get updated.
The notification does get triggered, it's when the user presses a button inside of it that no code gets executed. Looks something like this
I'd like to know if what I'm trying is even possible, because at this point I'm not sure.
The notifications are created using the zonedSchedule from the flutter local notifications plugin.
The app does not get opened when pressing one of the buttons in the notification.
The code is as follows:
class LocalNoticationsService {
LocalNoticationsService(
this._notificationsPlugin,
);
final FlutterLocalNotificationsPlugin _notificationsPlugin;
Future<void> init() async {
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings(
'img/path',// path to notification icon
);
final DarwinInitializationSettings initializationSettingsIOS = DarwinInitializationSettings(
requestSoundPermission: false,
requestBadgePermission: false,
requestAlertPermission: false,
defaultPresentAlert: true,
defaultPresentSound: true,
notificationCategories: [
DarwinNotificationCategory(
'category',
options: {
DarwinNotificationCategoryOption.allowAnnouncement,
},
actions: [
DarwinNotificationAction.plain(
'snoozeAction',
'snooze',
),
DarwinNotificationAction.plain(
'confirmAction',
'confirm',
options: {
DarwinNotificationActionOption.authenticationRequired,
},
),
],
),
],
);
final InitializationSettings initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsIOS,
);
await _notificationsPlugin.initialize(
initializationSettings,
onSelectNotification: _onSelectedNotification,
onSelectNotificationAction: onSelectNotificationAction,
);
final notificationOnLaunchDetails = await _notificationsPlugin.getNotificationAppLaunchDetails();
if (notificationOnLaunchDetails?.didNotificationLaunchApp ?? false) {
_onSelectedNotification(notificationOnLaunchDetails!.payload);
}
}
void _onSelectedNotification(String? payload) {
// Not relevant to this problem
}
Future<bool> _confirmAlarm(AlarmPayLoad alarmPayload) async {
// Update database
}
}
// Top level function
Future<void> onSelectNotificationAction(NotificationActionDetails details) async {
await Firebase.initializeApp();
final localNotificationsService = LocalNoticationsService(
FlutterLocalNotificationsPlugin()
);
await localNotificationsService.init();
final alarmPayload = AlarmPayLoad.fromJson(details.payload);
await localNotificationsService._confirmAlarm(alarmPayload)
}
Due to this all running in the background, I've been unable to find a way to log things. I've tried using the http package to send post request to a webhook with some data, but these do not seem to trigger when the app is terminated, but do work when in the app is in the foreground or in the background(not closed).
Any post or videos I've found online about flutter local notifications don't seem to cover this problem or are using firebase push notifications and the associated package for background handling.
I'd be very interested to hear any feedback on what might be going wrong or what might be the solution and how handling background notifications works. If you need additional information on the code, feel free to ask.
If you want to run it on background, follow the link here.

How can i send birthday wishes notifciations to user automatically when the day comes using Flutter

In my flutter app i am collecting the date of birth of user , now i want to send them birthday wishes as push notifications when the day comes , the notifications should be sent even when the user doesnt uses the app , like facebook ,gmail sends.
Someone suggested me of using broadcast for this , but as a beginner in flutter i cannot find a way about how to use it , or can someone please suggest another solution for it.
I used flutter_local_notifications as i implemented it in one of my pages it can only be triggered when user runs the app , whereas i want wishes to be sent automatically.
It will be very helpful if someone helped me out here.
Integrate firebase and there is a too Firebae cloud messaging or you can have your own site and implement it. However, cloud messaging is free.
You can take two ways: You do it from remote on your server than you send a notification (For istance by using Firebase) or you schedule a notification with flutter_local_notification.
I'll post you an example by using flutter_local_notification:
Let's say your user inputs something like DateTime birthday = DateTime(1996, 12, 12). Than you trigger the following:
int currentAge = DateTime.now().year - birthday.year;
//Notification setup
AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails('your channel id',
'your channel name', 'your channel description');
IOSNotificationDetails iOSPlatformChannelSpecifics =
IOSNotificationDetails();
NotificationDetails platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
//Iterate for 20 years
for(int i = 0; i<20; i++){
await flutterLocalNotificationsPlugin.schedule(
0,
'scheduled title',
'scheduled body',
birthday.add(Duration(years: currentAge+i)),
platformChannelSpecifics);
}
Done :)
Ps. Be carefull: DateTime contains also Hour, Minute, Seconds and microseconds. So, if you schedule it, do it properly.
Use this package,
flutter_local_notification
You can use it like this and use some kind of key value storage to check for which date/year it has been set and based on this check you could reset the notification for next year and so on.
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
initialize() async {
// This is how you initialize the local notification package in flutter.
// Please follow the link above to setup iOS and Android specify permission and configuration.
var initializationSettingsAndroid =
AndroidInitializationSettings('app_icon');
var initializationSettingsIOS = IOSInitializationSettings(
onDidReceiveLocalNotification: onDidReceiveLocalNotification,
);
var initializationSettings = InitializationSettings(
initializationSettingsAndroid,
initializationSettingsIOS,
);
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
onSelectNotification: onSelectNotification,
);
}
Future<void> scheduleUserBirthdayNotification({DateTime dob}) async {
// nScheduledDobId is your notification id should be integer.
// cancel the previous one before setting for next year.
await cancelNotification(withId: nScheduledDobId);
DateTime commingDate = DateTime.now();
final scheduledNotificationDateTime =
DateTime(commingDate.year, dob.month, dob.day, 6);
await scheduleNotification(
id: nScheduledDobId,
title: 'Happy Birthday! 🎂',
scheduledNotificationDateTime: scheduledNotificationDateTime,
body:
"We hope your special day will bring you lots of happiness, love, and fun.",
);
await KeyValueStorage().setDobNotificationDate(
scheduledNotificationDateTime,
);
}