I am developing a mobile app with flutter which needs to show a notification that can not be dismissed. So as soon as the notification is displayed it can not be swiped away. The only possiblity to dismiss it would be to disable notification from the application within the settings.
Currently I am using local_notifcation package, but I can’t see the possiblity to make the notification non-dismissable.
My current solution to have a semi-continuous notification is to show a notification repeatedly. This notification can be dismissed but it will pop up after some time using background_fetch package. This solution is not perfect, as the notification can be dismissed and backfround_fetch is not showing the notification every 15 minutes as set.
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:background_fetch/background_fetch.dart';
const String darwinNotificationCategoryPlain = 'plainCategory';
var flutterLocalNotificationsPlugin;
const BigPictureStyleInformation bigPictureStyleInformation =
BigPictureStyleInformation(FilePathAndroidBitmap(filePath));
// [Android-only] This "Headless Task" is run when the Android app is terminated with `enableHeadless: true`
// Be sure to annotate your callback function to avoid issues in release mode on Flutter >= 3.3.0
@pragma('vm:entry-point')
void backgroundFetchHeadlessTask(HeadlessTask task) async {
String taskId = task.taskId;
bool isTimeout = task.timeout;
if (isTimeout) {
// This task has exceeded its allowed running-time.
// You must stop what you're doing and immediately .finish(taskId)
print("[BackgroundFetch] Headless task timed-out: $taskId");
BackgroundFetch.finish(taskId);
return;
}
print('[BackgroundFetch] Headless event received.');
await displayDefaultNotification(flutterLocalNotificationsPlugin);
BackgroundFetch.finish(taskId);
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
// Initialize settings for Android and iOS (optional)
const AndroidInitializationSettings androidInitializationSettings =
AndroidInitializationSettings('@mipmap/ic_launcher');
const DarwinInitializationSettings iosInitializationSettings =
DarwinInitializationSettings(
onDidReceiveLocalNotification: onDidReceiveLocalNotification,
);
final InitializationSettings initializationSettings = InitializationSettings(
android: androidInitializationSettings,
iOS: iosInitializationSettings,
);
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
);
// final NotificationAppLaunchDetails? notificationAppLaunchDetails =
// await flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails();
// print(notificationAppLaunchDetails!.payload)
await checkForNotificationPermission();
displayDefaultNotification(flutterLocalNotificationsPlugin);
// displayDefaultNotification(flutterLocalNotificationsPlugin);
runApp(MyApp());
BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);
}
Future<void> onSelectNotification(String? payload) async {
// Handle when a notification is tapped
displayDefaultNotification(flutterLocalNotificationsPlugin);
print("[onSelectNotification] - Notification tapped: $payload");
}
Future<void> onDidReceiveLocalNotification(
int id, String? title, String? body, String? payload) async {
// Handle when a notification is received while the app is in the foreground
print(
"[onDidReceiveLocalNotification] - Notification received: $title, $body, $payload");
}
Future<void> displayDefaultNotification(
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin) async {
print("[displaying default notification] - ${DateTime.now()}");
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'3', // Change this to a unique channel ID
'My Channel', // Change this to a unique channel name
// 'Descriptor', // Change this to a unique channel description
styleInformation: bigPictureStyleInformation,
importance: Importance.low,
priority: Priority.low,
ongoing: true,
autoCancel: false,
enableVibration: false,
visibility: NotificationVisibility.public,
);
const DarwinNotificationDetails iosNotificationDetails =
DarwinNotificationDetails(
categoryIdentifier: darwinNotificationCategoryPlain,
);
const NotificationDetails platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
// android: androidNotificationDetailsNew,
iOS: iosNotificationDetails,
);
if (qrImageExists) {
debugNotificationTimeDifference =
debugNotificationTime.difference(DateTime.now());
await flutterLocalNotificationsPlugin.show(
1, // Notification ID (you can use a unique ID for each notification)
'Dein SOS QR Code',
'${debugNotificationTimeDifference} - Scanne diesen QR Code für notfallmedizinsche Informationen.',
platformChannelSpecifics,
);
debugNotificationTime = DateTime.now();
}
}
class _MyHomePageState extends State<MyHomePage> {
var selectedIndex = 0;
bool _enabled = true;
int _status = 0;
List<DateTime> _events = [];
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
// Configure BackgroundFetch.
int status = await BackgroundFetch.configure(
BackgroundFetchConfig(
minimumFetchInterval: 15,
stopOnTerminate: false,
enableHeadless: true,
requiresBatteryNotLow: false,
requiresCharging: false,
requiresStorageNotLow: false,
requiresDeviceIdle: false,
startOnBoot: true,
requiredNetworkType: NetworkType.NONE), (String taskId) async {
// <-- Event handler
// This is the fetch-event callback.
print("[BackgroundFetch] Event received $taskId");
setState(() {
_events.insert(0, DateTime.now());
});
print(_events);
await displayDefaultNotification(flutterLocalNotificationsPlugin);
// IMPORTANT: You must signal completion of your task or the OS can punish your app
// for taking too long in the background.
BackgroundFetch.finish(taskId);
}, (String taskId) async {
// <-- Task timeout handler.
// This task has exceeded its allowed running-time. You must stop what you're doing and immediately .finish(taskId)
print("[BackgroundFetch] TASK TIMEOUT taskId: $taskId");
BackgroundFetch.finish(taskId);
});
print('[BackgroundFetch] configure success: $status');
setState(() {
_status = status;
});
// _onClickEnable(_enabled);
BackgroundFetch.start();
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
}
@override
void initState() {
super.initState();
initPlatformState();
}
@override
Widget build(BuildContext context) {...}
}
The whole UI was spared out as it is not relevant for this question.
Is there a way to make the notification non-dismissable even if it means switching from local_notification package to some other package?
Pabart13 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.