Flutter Local Notifications Example

This article explains you how you can trigger local notifications in your flutter application.

Local notification is a way to inform or alert user about some information without use of internet. In this example, we are using flutter local notifications package to integrate local notification in both android and iOS platforms.

 

Add below dependency in your pubspec.yaml file

flutter_local_notifications: ^1.4.4+1
 
 

Flutter Local Notifications Changes In Android Platform

For local notifications in android, We need to add following permissions in android manifest file.

<uses-permission android:name=”android.permission.RECEIVE_BOOT_COMPLETED”/>
<uses-permission android:name=”android.permission.VIBRATE” />
 

We also need to add receivers in android manifest file. Add below lines under application tag in AndroidManifest.xml.

<receiver android:name= “com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver”>
<intent-filter>
<action android:name=”android.intent.action.BOOT_COMPLETED”></action>
</intent-filter>
</receiver>
<receiver android:name=”com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver” />
 
 

Request Permissions For Flutter Local Notifications In iOS Platform

We need to ask notification permission for iOS users to integrate local notifications.

void requestPermissions() {
    flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation
<IOSFlutterLocalNotificationsPlugin>()?.requestPermissions(
        alert: true,
        badge: true,
        sound: true,
    );
}
 
 

Initialize Flutter Local Notifications

First we initialize notification settings for android and iOS platform separately. For android platform, We must specify notification icon name otherwise notification will not be shown in android platform. Notification icon must be places under android res/drawable folder.

For iOS platform, You can set sound, badge and alert permissions as below. You can also specify function to onSelectNotification parameter to display new screen on click of notification. You can also pass information to new screen.

@override
void initState() {
super.initState();
var androidSettings = AndroidInitializationSettings(‘app_icon’);
var iOSSettings = IOSInitializationSettings(
    requestSoundPermission: false,
    requestBadgePermission: false,
    requestAlertPermission: false,
);

var initSetttings = InitializationSettings(androidSettings, iOSSettings);
flutterLocalNotificationsPlugin.initialize(initSetttings, onSelectNotification: onClickNotification);

}

Future onClickNotification(String payload) {
    Navigator.of(context).push(MaterialPageRoute(builder: (_) {
        return DestinationScreen(
            payload: payload,
        );
    }));
}

 
 

Simple Notification

You can specify particular notification settings for android and iOS platform as below. For android platform, You need to set notification channel id, name and description. You can also set priority and importance of notification in android platform.

Flutter local notification provides show method in which there are different parameters. Here you can set notification title, body and platform settings. You can also pass information to new screen with this payload parameter.

showSimpleNotification() async {
var androidDetails = AndroidNotificationDetails(‘id’, ‘channel ‘, ‘description’,
priority: Priority.High, importance: Importance.Max);
var iOSDetails = IOSNotificationDetails();
var platformDetails = new NotificationDetails(androidDetails, iOSDetails);
await flutterLocalNotificationsPlugin.show(0, ‘Flutter Local Notification’, ‘Flutter Simple Notification’,
platformDetails, payload: ‘Destination Screen (Simple Notification)’);
}
 
 

Schedule Notification

You can schedule notification after certain amount of time using schedule method for once. Here we schedule local notification after five seconds. Other parameters are same as simple notification.

Future<void> showScheduleNotification() async {
var scheduledNotificationDateTime = DateTime.now().add(Duration(seconds: 5));
var androidDetails = AndroidNotificationDetails(
    ‘channel_id’,
    ‘Channel Name’,
    ‘Channel Description’,
    icon: ‘app_icon’,
    largeIcon: DrawableResourceAndroidBitmap(‘app_icon’),
);
var iOSDetails = IOSNotificationDetails();
var platformDetails = NotificationDetails(androidDetails, iOSDetails);
await flutterLocalNotificationsPlugin.schedule(0, ‘Flutter Local Notification’, ‘Flutter Schedule Notification’, scheduledNotificationDateTime, platformDetails, payload: ‘Destination Screen(Schedule Notification)’);
}
 
 

Periodic Notification

You can schedule notification after certain amount of time periodically using periodicallyShow method. Here we schedule push notification after every minute.

Future<void> showPeriodicNotification() async {
const AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails(‘channel_id’, ‘Channel Name’, ‘Channel Description’);
const NotificationDetails notificationDetails = NotificationDetails(androidNotificationDetails, null);
await flutterLocalNotificationsPlugin.periodicallyShow(0, ‘Flutter Local Notification’, ‘Flutter Periodic Notification’, RepeatInterval.EveryMinute, notificationDetails, payload: ‘Destination Screen(Periodic Notification)’);
}
 
 

Picture Notification

You can display only picture notification in android platform as below.

Future<void> showBigPictureNotification() async {
var bigPictureStyleInformation = BigPictureStyleInformation(
    DrawableResourceAndroidBitmap(“cover_image”),
    largeIcon: DrawableResourceAndroidBitmap(“app_icon”),
    contentTitle: ‘Flutter Big Picture Notification Title’,
    summaryText: ‘Flutter Big Picture Notification Summary Text’,
);
var androidDetails = AndroidNotificationDetails(
    ‘channel_id’,
    ‘Channel Name’,
    ‘Channel Description’,
    styleInformation: bigPictureStyleInformation);
var platformDetails = NotificationDetails(androidDetails, null);
await flutterLocalNotificationsPlugin.show(0, ‘Flutter Local Notification’, ‘Flutter Big Picture Notification’, platformDetails, payload: ‘Destination Screen(Big Picture Notification)’);
}
 
 

Multiline Text Notification

You can display multiple text lines notification.

Future<void> showBigTextNotification() async {
const BigTextStyleInformation bigTextStyleInformation = BigTextStyleInformation(
    ‘Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.’,
    htmlFormatBigText: true,
    contentTitle: ‘Flutter Big Text Notification Title’,
    htmlFormatContentTitle: true,
    summaryText: ‘Flutter Big Text Notification Summary Text’,
    htmlFormatSummaryText: true,
);
const AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails(‘channel_id’, ‘Channel Name’, ‘Channel Description’, styleInformation: bigTextStyleInformation);
const NotificationDetails notificationDetails = NotificationDetails(androidNotificationDetails, null);
await flutterLocalNotificationsPlugin.show(0, ‘Flutter Local Notification’, ‘Flutter Big Text Notification’, notificationDetails, payload: ‘Destination Screen(Big Text Notification)’);
}
 
 

Insistent Notification

You can also trigger notification continuously as below.

Future<void> showInsistentNotification() async {
const int insistentFlag = 4;
final AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails(‘channel_id’, ‘Channel Name’, ‘Channel Description’,
    importance: Importance.Max,
    priority: Priority.High,
    ticker: ‘ticker’,
    additionalFlags: Int32List.fromList(<int>[insistentFlag]));
final NotificationDetails notificationDetails = NotificationDetails(androidPlatformChannelSpecifics, null);
await flutterLocalNotificationsPlugin.show(0, ‘Flutter Local Notification’, ‘Flutter Insistent Notification’, notificationDetails, payload: ‘Destination Screen(Insistent Notification)’);
}
 
 

Ongoing Notification

Ongoing notification is used to notify user that task is running like foreground service. This type of notification you can not be clear.

Future<void> showOngoingNotification() async {
const AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails(‘channel_id’, ‘Channel Name’, ‘Channel Description’,
    importance: Importance.Max,
priority: Priority.High,
    ongoing: true,
    autoCancel: false);
const NotificationDetails notificationDetails = NotificationDetails(androidNotificationDetails, null);
await flutterLocalNotificationsPlugin.show(0, ‘Flutter Local Notification’, ‘Flutter Ongoing Notification’, notificationDetails, payload: ‘Destination Screen(Ongoing Notification)’);
}
 
 

Progress Notification

In this notification, you can display progress of particular task.

Future<void> showProgressNotification() async {
const int maxProgress = 5;
for (int i = 0; i <= maxProgress; i++) {
await Future<void>.delayed(const Duration(seconds: 1), () async {
final AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails(‘channel_id’, ‘Channel Name’, ‘Channel Description’,
    channelShowBadge: false,
importance: Importance.Max,
    priority: Priority.High,
    onlyAlertOnce: true,
    showProgress: true,
    maxProgress: maxProgress,
    progress: i);
final NotificationDetails notificationDetails = NotificationDetails(androidNotificationDetails, null);
await flutterLocalNotificationsPlugin.show(0, ‘Flutter Local Notification’, ‘Flutter Progress Notification’, notificationDetails, payload: ‘Destination Screen(Progress Notification)’);
});
}
}
 
 
 

Final Code For Flutter Local Notifications

import 'dart:typed_data';

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

class LocalNotifications extends StatefulWidget {

  String title;

  LocalNotifications({this.title});

  @override
  _LocalNotificationsState createState() => _LocalNotificationsState();
}

class _LocalNotificationsState extends State<LocalNotifications> {

  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  @override
  void initState() {
    super.initState();
    requestPermissions();
    var androidSettings = AndroidInitializationSettings('app_icon');
    var iOSSettings = IOSInitializationSettings(
      requestSoundPermission: false,
      requestBadgePermission: false,
      requestAlertPermission: false,
    );

    var initSetttings = InitializationSettings(androidSettings, iOSSettings);
    flutterLocalNotificationsPlugin.initialize(initSetttings, onSelectNotification: onClickNotification);

  }

  void requestPermissions() {
    flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()?.requestPermissions(
      alert: true,
      badge: true,
      sound: true,
    );
  }

  Future onClickNotification(String payload) {
    Navigator.of(context).push(MaterialPageRoute(builder: (_) {
      return DestinationScreen(
        payload: payload,
      );
    }));
  }

  showSimpleNotification() async {
    var androidDetails = AndroidNotificationDetails('id', 'channel ', 'description',
        priority: Priority.High, importance: Importance.Max);
    var iOSDetails = IOSNotificationDetails();
    var platformDetails = new NotificationDetails(androidDetails, iOSDetails);
    await flutterLocalNotificationsPlugin.show(0, 'Flutter Local Notification', 'Flutter Simple Notification',
        platformDetails, payload: 'Destination Screen (Simple Notification)');
  }

  Future<void> showScheduleNotification() async {
    var scheduledNotificationDateTime = DateTime.now().add(Duration(seconds: 5));
    var androidDetails = AndroidNotificationDetails(
      'channel_id',
      'Channel Name',
      'Channel Description',
      icon: 'app_icon',
      largeIcon: DrawableResourceAndroidBitmap('app_icon'),
    );
    var iOSDetails = IOSNotificationDetails();
    var platformDetails = NotificationDetails(androidDetails, iOSDetails);
    await flutterLocalNotificationsPlugin.schedule(0, 'Flutter Local Notification', 'Flutter Schedule Notification',
        scheduledNotificationDateTime, platformDetails, payload: 'Destination Screen(Schedule Notification)');
  }

  Future<void> showPeriodicNotification() async {
    const AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails('channel_id', 'Channel Name', 'Channel Description');
    const NotificationDetails notificationDetails = NotificationDetails(androidNotificationDetails, null);
    await flutterLocalNotificationsPlugin.periodicallyShow(0, 'Flutter Local Notification', 'Flutter Periodic Notification',
        RepeatInterval.EveryMinute, notificationDetails, payload: 'Destination Screen(Periodic Notification)');
  }

  Future<void> showBigPictureNotification() async {
    var bigPictureStyleInformation = BigPictureStyleInformation(
      DrawableResourceAndroidBitmap("cover_image"),
      largeIcon: DrawableResourceAndroidBitmap("app_icon"),
      contentTitle: 'Flutter Big Picture Notification Title',
      summaryText: 'Flutter Big Picture Notification Summary Text',
    );
    var androidDetails = AndroidNotificationDetails(
        'channel_id',
        'Channel Name',
        'Channel Description',
        styleInformation: bigPictureStyleInformation);
    var platformDetails = NotificationDetails(androidDetails, null);
    await flutterLocalNotificationsPlugin.show(0, 'Flutter Local Notification', 'Flutter Big Picture Notification',
        platformDetails, payload: 'Destination Screen(Big Picture Notification)');
  }

  Future<void> showBigTextNotification() async {
    const BigTextStyleInformation bigTextStyleInformation =
    BigTextStyleInformation(
      'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
      htmlFormatBigText: true,
      contentTitle: 'Flutter Big Text Notification Title',
      htmlFormatContentTitle: true,
      summaryText: 'Flutter Big Text Notification Summary Text',
      htmlFormatSummaryText: true,
    );
    const AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails('channel_id', 'Channel Name', 'Channel Description', styleInformation: bigTextStyleInformation);
    const NotificationDetails notificationDetails = NotificationDetails(androidNotificationDetails, null);
    await flutterLocalNotificationsPlugin.show(0, 'Flutter Local Notification', 'Flutter Big Text Notification',
        notificationDetails, payload: 'Destination Screen(Big Text Notification)');
  }

  Future<void> showInsistentNotification() async {
    const int insistentFlag = 4;
    final AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails('channel_id', 'Channel Name', 'Channel Description',
        importance: Importance.Max,
        priority: Priority.High,
        ticker: 'ticker',
        additionalFlags: Int32List.fromList(<int>[insistentFlag]));
    final NotificationDetails notificationDetails = NotificationDetails(androidPlatformChannelSpecifics, null);
    await flutterLocalNotificationsPlugin.show(0, 'Flutter Local Notification', 'Flutter Insistent Notification',
        notificationDetails, payload: 'Destination Screen(Insistent Notification)');
  }

  Future<void> showOngoingNotification() async {
    const AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails('channel_id', 'Channel Name', 'Channel Description',
        importance: Importance.Max,
        priority: Priority.High,
        ongoing: true,
        autoCancel: false);
    const NotificationDetails notificationDetails = NotificationDetails(androidNotificationDetails, null);
    await flutterLocalNotificationsPlugin.show(0, 'Flutter Local Notification', 'Flutter Ongoing Notification',
        notificationDetails, payload: 'Destination Screen(Ongoing Notification)');
  }

  Future<void> showProgressNotification() async {
    const int maxProgress = 5;
    for (int i = 0; i <= maxProgress; i++) {
      await Future<void>.delayed(const Duration(seconds: 1), () async {
        final AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails('channel_id', 'Channel Name', 'Channel Description',
            channelShowBadge: false,
            importance: Importance.Max,
            priority: Priority.High,
            onlyAlertOnce: true,
            showProgress: true,
            maxProgress: maxProgress,
            progress: i);
        final NotificationDetails notificationDetails = NotificationDetails(androidNotificationDetails, null);
        await flutterLocalNotificationsPlugin.show(0, 'Flutter Local Notification', 'Flutter Progress Notification',
            notificationDetails, payload: 'Destination Screen(Progress Notification)');
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: Container(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              RaisedButton(
                child: Text('Simple Notification'),
                onPressed: () => showSimpleNotification(),
              ),
              SizedBox(height: 15),
              RaisedButton(
                child: Text('Schedule Notification'),
                onPressed: () => showScheduleNotification(),
              ),
              SizedBox(height: 15),
              RaisedButton(
                child: Text('Periodic Notification'),
                onPressed: () => showPeriodicNotification(),
              ),
              SizedBox(height: 15),
              RaisedButton(
                child: Text('Big Picture Notification'),
                onPressed: () => showBigPictureNotification(),
              ),
              SizedBox(height: 15),
              RaisedButton(
                child: Text('Big Text Notification'),
                onPressed: () => showBigTextNotification(),
              ),
              SizedBox(height: 15),
              RaisedButton(
                child: Text('Insistent Notification'),
                onPressed: () => showInsistentNotification(),
              ),
              SizedBox(height: 15),
              RaisedButton(
                child: Text('OnGoing Notification'),
                onPressed: () => showOngoingNotification(),
              ),
              SizedBox(height: 15),
              RaisedButton(
                child: Text('Progress Notification'),
                onPressed: () => showProgressNotification(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
 
import 'package:flutter/material.dart';

class DestinationScreen extends StatelessWidget {

  String payload;

  DestinationScreen({this.payload});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
       child: Padding(padding: EdgeInsets.all(25),child: Text(payload, textAlign: TextAlign.center, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 30,))),
      )
    );
  }
}

 
 
 
 
flutter local notifications
 
 
flutter local notifications
 
 
 
flutter local notifications
 
 

Leave a Reply