Background local notifications in Flutter (original) (raw)

Last Updated : 10 Mar, 2025

Sometimes user wants some essential features like the latest news updates, latest articles updates, weather condition alert, complete his/her profile update, future events update and much more in his/ her Android or iOS device without opening App and if you would like to develop this kind of Android and iOS application then this article will help you to do so. In this process, we set up background jobs that periodically check updates about the latest events or alerts.

Flutter Local Notifications

It is a cross-platform plugin for displaying local notifications in a flutter application. It offers a bunch of features, such as scheduling when notifications should appear, periodically showing a notification (interval-based), handling when a user has tapped on a notification when the app is in the foreground, background, or terminated, specifying a custom notification sound, and much more.

Steps to Implement Background Local Notifications

Step 1: Create a new flutter application

Create a new Flutter application using the command Prompt. To create a new app, write the below command and run it.

flutter create app_name

To know more about it refer this article: Creating a Simple Application in Flutter

Step 2: Adding the Dependency

To add the dependency to the **pubspec.yaml file, add **image_picker as a dependency in the dependencies part of the pubspec.yaml file, as shown below:

Dart `

dependencies: flutter: sdk: flutter flutter_local_notifications: ^18.0.1

`

Now run the below command in the terminal.

flutter pub get

Step 3: Importing the Dependency

Use the below line of code in the **main.dart file, to import the **flutter_local_notifications dependency :

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

Step 4: Add permissions

**Android permissions:

Now, It's time to add some required permissions, open the ****'AndroidManifest.xml'** file from **app_name-> android -> app -> src -> main -> AndroidManifest.xml project directory structure and copy-paste following permissions.

**IOS permissions:

open the ****'Info.plist'** file from **app_name->ios->Runner->Info.plist project directory structure and copy-paste following permissions.

UIBackgroundModes

audio
fetch

Step 5: Follow below steps

- **Intialize Global Variable

Dart `

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

`

- **Intialize settings in main

initialize both android and ios settings in main function ,after initialize those settings to global variable.

Dart `

Future main() async { // Ensure Flutter bindings are initialized before using plugins. WidgetsFlutterBinding.ensureInitialized();

// Android initialization settings. const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('@mipmap/ic_launcher');

// iOS (Darwin) initialization settings. const DarwinInitializationSettings initializationSettingsDarwin = DarwinInitializationSettings( // Optionally, add a callback to handle notifications while the app is in foreground. // onDidReceiveLocalNotification: (id, title, body, payload) async { // // Handle iOS foreground notification. // }, );

// Combine both platform settings. const InitializationSettings initializationSettings = InitializationSettings( android: initializationSettingsAndroid, iOS: initializationSettingsDarwin, );

// Initialize the plugin with a callback for when a notification is tapped. await flutterLocalNotificationsPlugin.initialize(initializationSettings, onDidReceiveNotificationResponse: (NotificationResponse response) { // Handle notification tapped logic here. print('Notification payload: ${response.payload}'); });

runApp(const MyApp()); }

`

- Design button

design and develop button to send notification from mobile and call **_showNotifications functions which sends the notification.

Dart `

ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.green, foregroundColor: Colors.white, ), onPressed: _showNotification, child: const Text('Send Notification'), ),

`

To know more about ElevatedButton refer this article: Flutter – ElevatedButton Widget

- _showNotifications function

Android `

// Method to show a local notification. Future _showNotification() async { const AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails( 'your_channel_id', // Unique channel ID. 'your_channel_name', // Visible channel name. channelDescription: 'Your channel description', importance: Importance.max, priority: Priority.high, );

    // For iOS, you can add additional configuration inside DarwinNotificationDetails.
    // For this example, we use the Android-specific details.
    const NotificationDetails platformChannelSpecifics = NotificationDetails(
            android: androidPlatformChannelSpecifics,
    );
    
    await flutterLocalNotificationsPlugin.show(
          0, // Notification ID.
          'Hello!', // Notification title.
          'Button pressed notification', // Notification body.
          platformChannelSpecifics,
          payload: 'Default_Sound', // Optional payload.
    );

}

IOS

Future _showNotificationIOS() async { // iOS-specific notification details. const DarwinNotificationDetails iosNotificationDetails = DarwinNotificationDetails( presentAlert: true, // Display an alert when notification is delivered presentBadge: true, // Update the app icon badge number presentSound: true, // Play a sound );

// Create the notification details using iOS settings. const NotificationDetails notificationDetails = NotificationDetails( iOS: iosNotificationDetails, );

// Show the notification. await flutterLocalNotificationsPlugin.show( 0, // Notification ID; use a unique value if you plan to trigger multiple notifications. 'Hello iOS!', // Notification title. 'Button pressed notification on iOS', // Notification body. notificationDetails, payload: 'iOS_payload', // Optional payload that you can use to pass data. ); }

`

Now, It is time to code, open ****'main.dart'** file from **app_name-> lib -> main.dart project directory structure and copy-paste following the entire code.

**main.dart:

Dart `

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

// Create a global instance of // FlutterLocalNotificationsPlugin final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

Future main() async { // Ensure Flutter bindings are // initialized before using plugins WidgetsFlutterBinding.ensureInitialized();

// Android initialization settings const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('@mipmap/ic_launcher');

// iOS (Darwin) initialization settings const DarwinInitializationSettings initializationSettingsDarwin = DarwinInitializationSettings(

// Optionally, add a callback to handle notifications while the app is in foreground
// onDidReceiveLocalNotification: (id, title, body, payload) async {
//   // Handle iOS foreground notification
// },

);

// Combine both platform settings. const InitializationSettings initializationSettings = InitializationSettings( android: initializationSettingsAndroid, iOS: initializationSettingsDarwin, );

// Initialize the plugin with a callback // for when a notification is tapped await flutterLocalNotificationsPlugin.initialize(initializationSettings, onDidReceiveNotificationResponse: (NotificationResponse response) {

// Handle notification tapped logic here
print('Notification payload: ${response.payload}');

});

runApp(const MyApp()); }

class MyApp extends StatelessWidget { const MyApp({super.key});

@override Widget build(BuildContext context) { return MaterialApp( title: 'Notification Demo', theme: ThemeData( primarySwatch: Colors.green, ), debugShowCheckedModeBanner: false, home: const HomePage(title: 'Notification Demo'), ); } }

class HomePage extends StatefulWidget { final String title; const HomePage({super.key, required this.title});

@override State createState() => _HomePageState(); }

class _HomePageState extends State {

// Replace the _showNotification function accordingly // Method to show a local notification Future _showNotification() async { const AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails( 'your_channel_id', // Unique channel ID 'your_channel_name', // Visible channel name channelDescription: 'Your channel description', importance: Importance.max, priority: Priority.high, );

// For iOS, you can add additional configuration
// inside DarwinNotificationDetails
// For this example, we use the Android-specific details
const NotificationDetails platformChannelSpecifics = NotificationDetails(
  android: androidPlatformChannelSpecifics,
);

await flutterLocalNotificationsPlugin.show(
  0, // Notification ID.
  'Hello!', // Notification title.
  'Button pressed notification', // Notification body.
  platformChannelSpecifics,
  payload: 'Default_Sound', // Optional payload.
);

}

@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.green, foregroundColor: Colors.white, title: Text(widget.title), ), body: Center( child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.green, foregroundColor: Colors.white, ), onPressed: _showNotification, child: const Text('Send Notification'), ), ), ); } }

`

**Output: