最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Flutter Scheduled Notifications not working - Stack Overflow

programmeradmin3浏览0评论

I am building an app and want to send reminders about the tasks the user has to complete. For that I am using flutter_local_notifications: 18.0.1. The variables that I use in this class are below:

static final NotificationService _instance = NotificationService._internal();
  factory NotificationService() => _instance;

  NotificationService._internal(); // Private constructor

  final FlutterLocalNotificationsPlugin notificationsPlugin =
      FlutterLocalNotificationsPlugin();

  bool _isInitialized = false;

  bool get isInitialized => _isInitialized;

Below is the initNotification method for the NotificationService class I made using ChatGPT, which is called in the main() function:

Future<void> initNotification() async {
    if (_isInitialized) return;

    // Init timezone
    tz.initializeTimeZones();
    final String currentTimeZone = await FlutterTimezone.getLocalTimezone();
    tz.setLocalLocation(tz.getLocation(currentTimeZone));

    // Android init
    const AndroidInitializationSettings initSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');

    // iOS init
    const DarwinInitializationSettings initSettingsIOS =
        DarwinInitializationSettings(
      requestAlertPermission: true,
      requestSoundPermission: true,
      requestBadgePermission: true,
    );

    // Init settings
    const InitializationSettings initSettings = InitializationSettings(
      android: initSettingsAndroid,
      iOS: initSettingsIOS,
    );

    // Init notifications plugin
    await notificationsPlugin.initialize(initSettings);

    _isInitialized = true;
  }

The NotificationDetails:

    // Notification details setup
  NotificationDetails notificationDetails() {
    return const NotificationDetails(
      android: AndroidNotificationDetails(
        'daily_reminder',
        'Daily Reminders',
        channelDescription: 'Reminder to complete a goal',
        importance: Importance.max,
        priority: Priority.high,
      ),
      iOS: DarwinNotificationDetails(),
    );
  }

When I use notificationsPlugin.show(), that notification works like a charm. But if I try to schedule a notification, that does not work for some reason:

    Future<void> scheduleNotification({
    int id = 1,
    required String title,
    required String body,
    required int hour,
    required int min,
  }) async {
    final now = tz.TZDateTime.now(tz.local);

    var scheduledDate = tz.TZDateTime(
      tz.local,
      now.year,
      now.month,
      now.day,
      hour,
      min,
    );
    await Permission.scheduleExactAlarm.isDenied.then((value) {
      if (value) {
        Permission.scheduleExactAlarm.request();
      }
    });
    await notificationsPlugin.zonedSchedule(
      id,
      title,
      body,
      scheduledDate,
      notificationDetails(),
      uiLocalNotificationDateInterpretation:
          UILocalNotificationDateInterpretation.absoluteTime,
      androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
      matchDateTimeComponents: DateTimeComponents.time,
    );
  }

I do give the app all the permissions that it needs, namely the Permission.notification to send notifications in general, and Permission.scheduleExactAlarm to schedule the alarms. What am I doing wrong?

I am building an app and want to send reminders about the tasks the user has to complete. For that I am using flutter_local_notifications: 18.0.1. The variables that I use in this class are below:

static final NotificationService _instance = NotificationService._internal();
  factory NotificationService() => _instance;

  NotificationService._internal(); // Private constructor

  final FlutterLocalNotificationsPlugin notificationsPlugin =
      FlutterLocalNotificationsPlugin();

  bool _isInitialized = false;

  bool get isInitialized => _isInitialized;

Below is the initNotification method for the NotificationService class I made using ChatGPT, which is called in the main() function:

Future<void> initNotification() async {
    if (_isInitialized) return;

    // Init timezone
    tz.initializeTimeZones();
    final String currentTimeZone = await FlutterTimezone.getLocalTimezone();
    tz.setLocalLocation(tz.getLocation(currentTimeZone));

    // Android init
    const AndroidInitializationSettings initSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');

    // iOS init
    const DarwinInitializationSettings initSettingsIOS =
        DarwinInitializationSettings(
      requestAlertPermission: true,
      requestSoundPermission: true,
      requestBadgePermission: true,
    );

    // Init settings
    const InitializationSettings initSettings = InitializationSettings(
      android: initSettingsAndroid,
      iOS: initSettingsIOS,
    );

    // Init notifications plugin
    await notificationsPlugin.initialize(initSettings);

    _isInitialized = true;
  }

The NotificationDetails:

    // Notification details setup
  NotificationDetails notificationDetails() {
    return const NotificationDetails(
      android: AndroidNotificationDetails(
        'daily_reminder',
        'Daily Reminders',
        channelDescription: 'Reminder to complete a goal',
        importance: Importance.max,
        priority: Priority.high,
      ),
      iOS: DarwinNotificationDetails(),
    );
  }

When I use notificationsPlugin.show(), that notification works like a charm. But if I try to schedule a notification, that does not work for some reason:

    Future<void> scheduleNotification({
    int id = 1,
    required String title,
    required String body,
    required int hour,
    required int min,
  }) async {
    final now = tz.TZDateTime.now(tz.local);

    var scheduledDate = tz.TZDateTime(
      tz.local,
      now.year,
      now.month,
      now.day,
      hour,
      min,
    );
    await Permission.scheduleExactAlarm.isDenied.then((value) {
      if (value) {
        Permission.scheduleExactAlarm.request();
      }
    });
    await notificationsPlugin.zonedSchedule(
      id,
      title,
      body,
      scheduledDate,
      notificationDetails(),
      uiLocalNotificationDateInterpretation:
          UILocalNotificationDateInterpretation.absoluteTime,
      androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
      matchDateTimeComponents: DateTimeComponents.time,
    );
  }

I do give the app all the permissions that it needs, namely the Permission.notification to send notifications in general, and Permission.scheduleExactAlarm to schedule the alarms. What am I doing wrong?

Share Improve this question edited Feb 17 at 16:21 Frank van Puffelen 600k85 gold badges889 silver badges859 bronze badges asked Feb 17 at 4:42 Ali AhmedAli Ahmed 116 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 0

Are you testing on an Android or iOS device?

On Android, depending on the system, you need to make sure that the battery settings do not close the application in the background. If this is the case, you need to change this setting to allow the application to run in the background.

I don't know the flutter_local_notifications plugin but the doc says you have to ask for permission like this:

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin>().requestNotificationsPermission();

The doc : https://pub.dev/packages/flutter_local_notifications#requesting-permissions-on-android-13-or-higher

发布评论

评论列表(0)

  1. 暂无评论