Flutter: Create a pdf file, show download notification and Open it when user click on notification

Issue

I am working on a flutter app. I am creating a pdf file in the "Downloads" folder, after creating the file in the "Downloads" folder, showing a notification "Download Completed" using the "local_notification" plugin.

Now I want to show that pdf when the user clicks on the notification. Can anybody guide me on how I can do that?

Below is my code

final android = AndroidNotificationDetails('0', 'Adun Accounts',
        channelDescription: 'channel description',
        priority: Priority.high,
        importance: Importance.max,
        icon: '');
    final iOS = IOSNotificationDetails();
    final platform = NotificationDetails(android: android, iOS: iOS);

    await flutterLocalNotificationsPlugin.show(
        0, // notification id
        fileName,
        'Download complete.',
        platform);

Solution

show() has a parameter called payload , you can pass the path to the pdf file here. Add the plugin open_file in your pubspec.yaml. Then inside main.dart, add the following code

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

Future<void> initNotification() async {
// initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
  const AndroidInitializationSettings initializationSettingsAndroid =
      AndroidInitializationSettings('notification_icon');
  final IOSInitializationSettings initializationSettingsIOS =
      IOSInitializationSettings();
  final MacOSInitializationSettings initializationSettingsMacOS =
      MacOSInitializationSettings();
  final InitializationSettings initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
      macOS: initializationSettingsMacOS);
  await flutterLocalNotificationsPlugin.initialize(initializationSettings,
      onSelectNotification: (String? payload) {
    if (payload != null) OpenFile.open(payload);
  });
}

Note: This function should not be inside any class.

Answered By – Chinmay Kabi

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *