local_notifications 0.0.7

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 82

LocalNotification Flutter Plugin

Plugin is no longer actively developed

I currently don't have plans to continue active development of this plugin. If something is not working or a feature is missing, feel free to submit a pull request. Otherwise, check out flutter_local_notifications.

Introduction

LocalNotifications is an easy way to create notifications on both Android and iOS.

pub package

Platforms

Currently the following platforms are supported

  • All Android versions that Flutter supports (4.1+ or SDK 16+)
  • iOS 10 or higher

A goal is to bring this dependencies down as much as possible.

Features

  • Create Notification with custom Title and Content
  • Create Notification with Custom Callback
  • Create Notification with multiple Actions
  • [Android Only] Create Notification with an Image
  • [Android Only] Create Notification which is Undismissable
  • [Android Only] Set Priority / Importance of Notification
  • [Android Only] Create a Notification with a custom vibrate pattern
  • Remove Notification by id

Installation

Simply add this package to your pubspec.yaml

dependencies:
  local_notifications: any

Then run flutter packages get to install the package.

For iOS, There is an issue with the flutter framework (https://github.com/flutter/flutter/issues/16097) that will cause build errors in projects initialized with objective-c iOS code when using plugins written in swift (as is the case with this plugin). To get around this for an existing project, see this comment. For new projects, just create the project using swift with flutter create -i swift

Add Service and Permission to AndroidManifest

To have the notification run code in the background (on click of either the notification itself or its actions), you must add the LocalNotificationsService to your app's manifest.

First locate your AndroidManifest.xml file, which is located at

android/app/src/main/AndroidManifest.xml

Then add the following Tag to the application node

<service
    android:name="com.mythichelm.localnotifications.services.LocalNotificationsService"
    android:exported="false" />

An example how it should look like can be found HERE

To support Android 4.1 and 4.2, you also need to add the following to inside the manifest node. There should already be an existing permission for INTERNET, just add this below that. For a full explanation why this is needed, see this issue

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

Send your first notification

Sending a basic notification is simple. (If running on an Android 8.0+ device, see bottom section "Sending Notifications on Android 8.0+")

await LocalNotifications.createNotification(
    title: "Basic",
    content: "Notification",
    id: 0
);

When you want to create multiple notifications make sure to assign each one an unique id

await LocalNotifications.createNotification(
    title: "My First Notification",
    content: "SomeContent"
    id: 0
);

await LocalNotifications.createNotification(
    title: "My Second Notification",
    content: "SomeContent"
    id: 1
);

Delete Notifications

You can delete the notifications by calling removeNotification with the notification id

int notificationId = 0;

await LocalNotifications.createNotification(
    title: "My First Notification",
    content: "SomeContent"
    id: notificationId
);

await LocalNotifications.removeNotification(notificationId);

Notification with custom callback

You can create notifications, which execute a custom callback in the background instead of launching the app.

onNotificationClick(String payload) {
	// payload is "some payload"
	print('Running in background and received payload: $payload');
}

int id = await LocalNotifications.createNotification(
    title: "Notification",
    content: "With custom callback",
    id: 0,
    onNotificationClick: new NotificationAction(
        actionText: "some action", // Note: only works for iOS
        callback: onNotificationClick,
        payload: "some payload"
    )
);

Notifications with multiple actions

You can create notifications which have multiple action buttons

handleCustomActionClick(String payload) {
    if(payload == "secondAction") {
        LocalNotifications.removeNotification(0);
    }
}

int id = await LocalNotifications.createNotification(
    title: "Multiple Actions",
    content: 'With custom callbacks',
    id: 0,
    onNotificationClick: new NotificationAction(
        actionText: "Some action",
        callback: onNotificationClick,
        payload: "Some payload",
        launchesApp: false
    ),
    actions: [
        new NotificationAction(
            actionText: "First",
            callback: handleCustomActionClick,
            payload: "firstAction",
            launchesApp: true
        ),
        new NotificationAction(
            actionText: "Second",
            callback: handleCustomActionClick,
            payload: "secondAction",
            launchesApp: false
        )
    ]
);

Sending Notifications on Android 8.0+

For Android 8.0+, you must first create a Notification Channel and associate this channel with every notification you create, otherwise the notifications will not be shown. Read about them in the Android SDK docs.

// Initialize your Notification channel object
static const AndroidNotificationChannel channel = const AndroidNotificationChannel(
      id: 'default_notification',
      name: 'Default',
      description: 'Grant this app the ability to show notifications',
      importance: AndroidNotificationImportance.HIGH
);

// Create the notification channel (this is a no-op on iOS and android <8.0 devices)
// Only need to run this one time per App install, any calls after that will be a no-op at the native level
// but will still need to use the platform channel. For this reason, avoid calling this except for the 
// first time you need to create the channel.
await LocalNotifications.createAndroidNotificationChannel(channel: channel);

// Create your notification, providing the channel info
await LocalNotifications.createNotification(
    title: "Basic",
    content: "Notification",
    id: 0,
    androidSettings: new AndroidSettings(
        channel: channel
    )
);

Send a notification that shows a heads up notification on Android and iOS

The below code is an example to have your notifications be shown as a heads up notification on iOS and all Android versions. Some of the values used in the constructors are the same as the constructors default values, but I'm being explicit here to show exactly what values you need.

// Initialize your Notification channel object
// For a heads up notification, the importance must be HIGH
static const AndroidNotificationChannel channel = const AndroidNotificationChannel(
      id: 'some_channel_id',
      name: 'My app feature that requires notifications',
      description: 'Grant this app the ability to show notifications for this app feature',
      importance: AndroidNotificationImportance.HIGH, // default value for constructor
      vibratePattern: AndroidVibratePatterns.DEFAULT, // default value for constructor
);

// Create the notification channel (this is a no-op on iOS and android <8.0 devices)
// Only need to run this one time per channel to initialize, any calls after that will be a no-op at the native level
// but will still need to use the platform channel. For this reason, avoid calling this except for the 
// first time you need to create the channel.
await LocalNotifications.createAndroidNotificationChannel(channel: channel);

// Create your notification, providing the channel info
await LocalNotifications.createNotification(
    title: "Basic",
    content: "Notification",
    id: 0,
    androidSettings: new AndroidSettings(
        channel: channel,
        priority: AndroidNotificationPriority.HIGH, // default value for constructor
        vibratePattern: AndroidVibratePatterns.DEFAULT, // default value for constructor
    ),
    iOSSettings: new iOSSettings (
        presentWhileAppOpen: true, // default value for constructor
    ),
);

[0.0.6] - April 12, 2018

  • Fix the support library dependency

[0.0.5] - April 12, 2018

  • Added support back for earlier Android versions. All versions supported by Flutter are supported by the plugin.
  • Removed deprecation and unchecked warnings that appeared when using the plugin.

[0.0.4] - April 11, 2018

  • Added ability to set a custom vibrate pattern on Android

[0.0.3] - April 8, 2018

  • Added setLogging method to enable/disable extra logging for help with debugging
  • Added support for Android 8.0+ with ability to create notification channels

[0.0.2] - April 3, 2018

  • createNotification parameter "id" is now required and no longer returns anything
  • removeNotification no longer returns anything
  • On Android, the default notification importance is high (was ANDROID_IMPORTANCE_DEFAULT)
  • Fixed exception thrown in createNotification when using Dart 2
  • Android min SDK supported is now 23 (this was always the case, it is now just formerly specified in the project's gradle)

[0.0.1] - March 24, 2018

  • Initial release of plugin
  • Below is a table indicating the features supported in this release
FeatureAndroidios
Create local notification with custom title and content<ul><li> - [x] </li></ul><ul><li> - [x] </li></ul>
Create local notification with custom actions with custom callbacks<ul><li> - [x] </li></ul><ul><li> - [x] </li></ul>
Dismiss local notification which is already delivered<ul><li> - [x] </li></ul><ul><li> - [x] </li></ul>
Create local notification with an image<ul><li> - [x] </li></ul><ul><li> - [ ] </li></ul>
Create local notification which is undismissable<ul><li> - [x] </li></ul><ul><li> - [ ] </li></ul>

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:local_notifications/local_notifications.dart';
import 'dart:async';

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

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => new MyAppState();
}

class MyAppState extends State<MyApp> {

  String _imageUrl = 'https://flutter.io/images/catalog-widget-placeholder.png';
  String _text;
  bool loggingEnabled = false;

  onNotificationClick(String payload) {
    setState(() {
      _text = 'in onNotificationClick with payload: $payload';
    });
  }

  onReplyClick(String payload) {
    setState(() {
      _text = 'in onReplyClick with payload: $payload';
    });
    LocalNotifications.removeNotification(0);
  }

  void removeNotify(String payload) async {
    await LocalNotifications.removeNotification(0);
  }

  static const AndroidNotificationChannel channel = const AndroidNotificationChannel(
      id: 'default_notification11',
      name: 'CustomNotificationChannel',
      description: 'Grant this app the ability to show notifications',
      importance: AndroidNotificationChannelImportance.HIGH,
      vibratePattern: AndroidVibratePatterns.DEFAULT,
  );

  Widget _getAddNotificationChannelButton() {
    return new RaisedButton(
      child: new Text('Create a notification channel (Android 8.0+)'),
      onPressed: () async {
        await LocalNotifications.createAndroidNotificationChannel(
            channel: channel
        );
      },
    );
  }

  Widget _getRemoveNotificationChannelButton() {
    return new RaisedButton(
      child: new Text('Remove a notification channel (Android 8.0+)'),
      onPressed: () async {
        await LocalNotifications.removeAndroidNotificationChannel(
            channel: channel
        );
      },
    );
  }

  Widget _enableLogging() {
    return new Row(
      children: <Widget>[
        new Switch(value: loggingEnabled, onChanged: (val) async {
          setState((){
            loggingEnabled = val;
          });
          await LocalNotifications.setLogging(val);
        }),
        new Text('Enable or Disable logging')
      ],
    );
  }

  Widget _getBasicNotification() {
    return new RaisedButton(
      onPressed: () async {
        await LocalNotifications.createNotification(
          id: 0,
          title: 'Basic',
          content: 'some basic notification',
          androidSettings: new AndroidSettings(
            isOngoing: false,
            channel: channel,
            priority: AndroidNotificationPriority.HIGH,
          ),
          onNotificationClick: new NotificationAction(
              actionText: "some action",
              callback: removeNotify,
              payload: ""
          )
        );
      },
      child: new Text('Create basic notification'),
    );
  }

  Widget _getNotificationWithImage() {
    return new RaisedButton(
        onPressed: () async {
          await LocalNotifications.createNotification(
            id: 0,
            title: 'Image',
            content: 'some notification with an image',
            imageUrl: _imageUrl,
          );
        },
        child: new Text('Create notification with image')
    );
  }

  Widget _getUndismissableNotification() {
    return new RaisedButton(
        onPressed: () async {
          await LocalNotifications.createNotification(
              id: 0,
              title: 'No swiping',
              content: 'Can\'t swipe this away',
              imageUrl: _imageUrl,
              androidSettings: new AndroidSettings(
                isOngoing: true
              )
          );
        },
        child: new Text('Create undismissable notification')
    );
  }

  Widget _getRemoveNotification() {
    return new RaisedButton(
      onPressed: () async {
        // remove notificatino by id,
        // all examples don't provide an id, so it defaults to 0
        await LocalNotifications.removeNotification(0);
      },
      child: new Text('Remove notification'),
    );
  }

  Widget _getNotificationWithCallbackAndPayload() {
    return new RaisedButton(
      onPressed: () async {
        await LocalNotifications.createNotification(
          id: 0,
            title: 'Callback and payload notif',
            content: 'Some content',
            onNotificationClick: new NotificationAction(
                actionText: "some action", // Note: action text gets ignored here, as android can't display this anywhere
                callback: onNotificationClick,
                payload: "some payload"
            ),
        );
      },
      child: new Text('Create notification with payload and callback'),
    );
  }

  Widget _getNotificationWithCallbackAndPayloadInBackground() {
    return new RaisedButton(
      onPressed: () async {
        await LocalNotifications.createNotification(
          id: 0,
          title: 'Callback and payload notif',
          content: 'Some content',
          onNotificationClick: new NotificationAction(
              actionText:  "some action", // Note: action text gets ignored here, as android can't display this anywhere
              callback: onNotificationClick,
              payload: "some payload without launching the app",
            launchesApp: false
          ),
        );
      },
      child: new Text('Create notification that executes callback without launching app'),
    );
  }

  Widget _getNotificationWithMultipleActionsAndPayloads() {
    return new RaisedButton(
      onPressed: () async {
        await LocalNotifications.createNotification(
            id: 0,
            title: 'Multiple actions',
            content: '... and unique callbacks and/or payloads for each',
            imageUrl: _imageUrl,
            onNotificationClick: new NotificationAction(
                actionText: "some action",
                callback: onNotificationClick,
                payload: "some payload",
                launchesApp: false
            ),
            actions: [
              new NotificationAction(
                  actionText: "First",
                  callback: onReplyClick,
                  payload: "firstAction",
                  launchesApp: true
              ),
              new NotificationAction(
                  actionText: "Second",
                  callback: onReplyClick,
                  payload: "secondAction",
                  launchesApp: false
              ),
              new NotificationAction(
                  actionText: "Third",
                  callback: onReplyClick,
                  payload: "thirdAction",
                  launchesApp: false
              ),
            ]
        );
      },
      child: new Text('Create notification with multiple actions'),
    );
  }

  Widget _getNotificationWithAnonymousFunctionAsCallback() {
    return new RaisedButton(
        child: new Text('Create notification with anonymous function as callback using a callbackName'),
        onPressed: () async {
          await LocalNotifications.createNotification(
            id: 0,
            title: 'Anonymous callback',
            content: '... using anonymous callback with provided callbackName',
            onNotificationClick: new NotificationAction(
              actionText: '', //ignored
              callback: (String payload) {
                setState((){
                  _text = payload;
                });
              },
              payload: 'payload with anonymous function',
              callbackName: 'anonymousName'
            ),
            actions: [
              new NotificationAction(
                actionText: 'anon',
                callback: (String payload) {
                  setState(() {
                    _text = payload;
                  });
                },
                payload: 'payload from action with anonymous action',
                callbackName: 'anonymousAction',
              )
            ]
          );
        }
    );
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('Notification example'),
        ),
        body: new Center(
          child: new Column(
            children: <Widget>[
              _enableLogging(),
              _getBasicNotification(),
              _getNotificationWithImage(),
              _getUndismissableNotification(),
              _getRemoveNotification(),
              _getNotificationWithCallbackAndPayload(),
              _getNotificationWithCallbackAndPayloadInBackground(),
              _getNotificationWithMultipleActionsAndPayloads(),
              _getNotificationWithAnonymousFunctionAsCallback(),
              _getAddNotificationChannelButton(),
              _getRemoveNotificationChannelButton(),
              new Text(_text ?? "Click a notification with a payload to see the results here")
            ],
          ),
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  local_notifications: ^0.0.7

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter packages get

Alternatively, your editor might support flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:local_notifications/local_notifications.dart';
  
Version Uploaded Documentation Archive
0.0.7 Jun 15, 2018 Go to the documentation of local_notifications 0.0.7 Download local_notifications 0.0.7 archive
0.0.6 Apr 13, 2018 Go to the documentation of local_notifications 0.0.6 Download local_notifications 0.0.6 archive
0.0.5 Apr 13, 2018 Go to the documentation of local_notifications 0.0.5 Download local_notifications 0.0.5 archive
0.0.4 Apr 12, 2018 Go to the documentation of local_notifications 0.0.4 Download local_notifications 0.0.4 archive
0.0.3 Apr 9, 2018 Go to the documentation of local_notifications 0.0.3 Download local_notifications 0.0.3 archive
0.0.2 Apr 4, 2018 Go to the documentation of local_notifications 0.0.2 Download local_notifications 0.0.2 archive
0.0.1 Mar 24, 2018 Go to the documentation of local_notifications 0.0.1 Download local_notifications 0.0.1 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
84
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
50
Overall:
Weighted score of the above. [more]
82
Learn more about scoring.

We analyzed this package on Dec 5, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.1.0
  • pana: 0.12.7
  • Flutter: 1.0.0

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Maintenance issues and suggestions

Use constrained dependencies. (-20 points)

The pubspec.yaml contains 1 dependency without version constraints. Specify version ranges for the following dependencies: meta.

The description is too short. (-20 points)

Add more detail about the package, what it does and what is its target use case. Try to write at least 60 characters.

Package is pre-v0.1 release. (-10 points)

While there is nothing inherently wrong with versions of 0.0.*, it usually means that the author is still experimenting with the general direction of the API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.19.0 <3.0.0
flutter 0.0.0
meta any 1.1.6
Transitive dependencies
collection 1.14.11
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test
local_notifications_example