Flutter local notifications

Flutter Local Notifications

Flutter Local Notifications is a plugin that allows you to display local notifications in your Flutter app. It provides an easy and customizable way to show notifications from within your app, even when it is in the background or closed.

Installation:

To use Flutter Local Notifications in your project, add the following dependency to your `pubspec.yaml` file:

dependencies:
  flutter_local_notifications: ^8.2.0

Initialization:

Before using local notifications, you need to initialize the plugin in your app. This typically happens in your main.dart file:

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // Initialize the plugin
  await flutterLocalNotificationsPlugin.initialize(
    InitializationSettings(
      android: AndroidInitializationSettings('@mipmap/ic_launcher'),
      iOS: IOSInitializationSettings(),
    ),
    onSelectNotification: (String? payload) async {
      // Handle notification tap
      // You can navigate to a specific screen or execute any desired logic here
    },
  );
  
  runApp(MyApp());
}

Scheduling Notifications:

To schedule a notification, you can use the `flutterLocalNotificationsPlugin.schedule` method. Here’s an example of scheduling a notification to appear after 5 seconds:

const AndroidNotificationDetails androidPlatformChannelSpecifics =
  AndroidNotificationDetails(
    'your channel id',
    'your channel name',
    'your channel description',
    importance: Importance.max,
    priority: Priority.high,
  );
const NotificationDetails platformChannelSpecifics =
  NotificationDetails(android: androidPlatformChannelSpecifics);

// Schedule the notification
await flutterLocalNotificationsPlugin.zonedSchedule(
  0,
  'Hello',
  'This is a scheduled notification',
  tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
  platformChannelSpecifics,
  androidAllowWhileIdle: true,
);

Handling Tapped Notifications:

When a user taps on a notification, you can handle the tap by providing an `onSelectNotification` callback when initializing the plugin. Inside this callback, you can handle the tap event as per your app’s requirements.

Customization:

Flutter Local Notifications allows you to customize various aspects of the notifications, including title, content, icon, sound, vibration pattern, and more. You can refer to the official documentation of the plugin for comprehensive examples and instructions on how to customize the notifications based on your needs.

With Flutter Local Notifications, you can easily integrate local notifications into your Flutter app and provide timely updates and reminders to your users.

Leave a comment