The answer consists of two parts:
- Creating heads-up notification.
- Showing action buttons in the notification.
1 ** Creating heads-up notification
we are gonna use this package awesome_notifications.
This how to initialize it in the main()
method of your project
AwesomeNotifications().initialize(
// set the icon to null if you want to use the default app icon
null,
[
NotificationChannel(
channelGroupKey: 'channel_group_key',
channelKey: 'channel_key',
channelName: 'channel_name',
channelDescription: 'channel_description',
importance: NotificationImportance.Max,
)
],
debug: true,
);
Android initialization only:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example">
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<application>
...
<activity
android:name=".MainActivity"
android:showOnLockScreen="true"
android:showWhenLocked="true"
android:turnScreenOn="true">
...
</activity>
...
</application>
</manifest>
Note: On iOS, you need to request for notifications permissions. And on Android 11, you need to request for fullScreenIntent
. Here's the code (put it in initState()
or whatever):
AwesomeNotifications().isNotificationAllowed().then(
(isAllowed) {
//It would be more appropriate if you can show your own dialog
//to the user before requesting the notifications permissons.
if (!isAllowed) {
AwesomeNotifications().requestPermissionToSendNotifications(
permissions: [
NotificationPermission.Alert,
NotificationPermission.Sound,
NotificationPermission.Badge,
NotificationPermission.Vibration,
NotificationPermission.Light,
NotificationPermission.FullScreenIntent,
],
);
}
}
);
And how to create the notification, put it whenever you need to fire the notification:
AwesomeNotifications().createNotification(
content: NotificationContent(
id: 10,
channelKey: 'channel key' //Same as above in initilize,
title: title,
body: body,
wakeUpScreen: true,
fullScreenIntent: true,
criticalAlert: true,
//Other parameters
),
);
2 ** Showing action buttons in the notification
In the previous code snippet when creating the notification, you can add the action buttons to it like that:
AwesomeNotifications().createNotification(
//...
actionButtons: <NotificationActionButton>[
NotificationActionButton(key: 'accept', label: 'Accept'),
NotificationActionButton(key: 'reject', label: 'Reject'),
],
);
You can add icons, text fields and so many other things. Look here for more.
And to listen for the tapped button, here's the code:
AwesomeNotifications().actionStream.listen(
(ReceivedAction receivedAction) {
if (receivedAction.buttonKeyPressed == 'accept') {
//Your code goes here
} else if (receivedAction.buttonKeyPressed == 'reject') {
//Your code goes here
}
//Here if the user clicks on the notification itself
//without any button
},
);
The awesome_notifications package is so extensive, I recommend you to learn about it more from their page.