Scheduling Multiple Time-Specific Local Notifications in Flutter

Scheduling Multiple Time-Specific Local Notifications in Flutter

Local notifications are a powerful way to engage users and remind them of important events or tasks in your Flutter app. This article will guide you through the process of scheduling multiple time-specific local notifications effectively, providing a clear and practical approach.

Prerequisites

  • Flutter installed and configured
  • Basic understanding of Flutter development
  • Familiarity with Dart programming language

Setting Up the Environment

1. Install the Plugin

flutter pub add flutter_local_notifications

2. Import the Plugin

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

Scheduling Notifications

1. Create a Notification Channel

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
var initializationSettingsAndroid = AndroidInitializationSettings('app_icon'); // Replace 'app_icon' with your icon
var initializationSettingsIOS = IOSInitializationSettings(requestSoundPermission: true, requestBadgePermission: true, requestAlertPermission: true);
var initializationSettings = InitializationSettings(android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings);

2. Define Notification Details

var androidPlatformChannelSpecifics = AndroidNotificationDetails('channel ID', 'channel name', importance: Importance.max, priority: Priority.high, sound: RawResourceAndroidNotificationSound('sound'));
var iOSPlatformChannelSpecifics = IOSNotificationDetails(sound: 'sound.wav');
var platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics, iOS: iOSPlatformChannelSpecifics);

3. Schedule Multiple Notifications

// Schedule notification for 10 seconds from now
await flutterLocalNotificationsPlugin.schedule(0, 'Notification Title', 'Notification Body', DateTime.now().add(Duration(seconds: 10)), platformChannelSpecifics);

// Schedule notification for 1 minute from now
await flutterLocalNotificationsPlugin.schedule(1, 'Another Notification', 'This is another notification', DateTime.now().add(Duration(minutes: 1)), platformChannelSpecifics);

// Schedule notification for 2 hours from now
await flutterLocalNotificationsPlugin.schedule(2, 'Third Notification', 'Third notification message', DateTime.now().add(Duration(hours: 2)), platformChannelSpecifics);

Handling Notification Tapping

// Listen for notification taps
flutterLocalNotificationsPlugin.initialize(initializationSettings, onSelectNotification: (String? payload) async {
  // Handle the notification tap
  print('Notification tapped: $payload');
});

Code Example

import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  @override
  void initState() {
    super.initState();
    _initializeNotifications();
  }

  Future _initializeNotifications() async {
    var initializationSettingsAndroid = AndroidInitializationSettings('app_icon'); // Replace 'app_icon' with your icon
    var initializationSettingsIOS = IOSInitializationSettings(requestSoundPermission: true, requestBadgePermission: true, requestAlertPermission: true);
    var initializationSettings = InitializationSettings(android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
    await flutterLocalNotificationsPlugin.initialize(initializationSettings, onSelectNotification: (String? payload) async {
      print('Notification tapped: $payload');
    });

    // Schedule notifications
    await flutterLocalNotificationsPlugin.schedule(0, 'Notification Title', 'Notification Body', DateTime.now().add(Duration(seconds: 10)), _platformChannelSpecifics);
    await flutterLocalNotificationsPlugin.schedule(1, 'Another Notification', 'This is another notification', DateTime.now().add(Duration(minutes: 1)), _platformChannelSpecifics);
    await flutterLocalNotificationsPlugin.schedule(2, 'Third Notification', 'Third notification message', DateTime.now().add(Duration(hours: 2)), _platformChannelSpecifics);
  }

  NotificationDetails get _platformChannelSpecifics {
    var androidPlatformChannelSpecifics = AndroidNotificationDetails('channel ID', 'channel name', importance: Importance.max, priority: Priority.high, sound: RawResourceAndroidNotificationSound('sound'));
    var iOSPlatformChannelSpecifics = IOSNotificationDetails(sound: 'sound.wav');
    return NotificationDetails(android: androidPlatformChannelSpecifics, iOS: iOSPlatformChannelSpecifics);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Local Notifications'),
      ),
      body: Center(
        child: Text('Notifications scheduled!'),
      ),
    );
  }
}

Output

Notification tapped: null

This example schedules three notifications: one in 10 seconds, one in 1 minute, and one in 2 hours. When the notifications are tapped, the console will print ‘Notification tapped: null’ since no payload is provided in this example. You can customize the payload for each notification to provide more information when the user taps on it.

Conclusion

Scheduling multiple time-specific local notifications in Flutter is a straightforward process. This guide has provided a comprehensive approach, including setting up the environment, defining notification details, scheduling notifications, and handling taps. By utilizing these steps, you can effectively enhance your Flutter app with powerful and engaging notification capabilities.


Leave a Reply

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