locally 0.2.6+9

  • Readme
  • Changelog
  • Example
  • Installing
  • 84

Locally #

pub package

flutter local notification #

Locally helps developers create local notification with flutter on both Android and IOS platforms, it depends on the flutter_local_notification plugin and tries to make usage more simple and user friendly.

Screenshots as obtained from flutter_local_notification #

AndroidiOS

Acknowledgements #

Usage #

Show basic notification #

//
Locally locally = Locally(
          context: context,
          payload: 'test',
          pageRoute: MaterialPageRoute(builder: (context) => SecondScreen(title: title.text, message: message.text)),
          appIcon: 'mipmap/ic_launcher',
      );

      locally.show(title: title.text, message: message.text);

show notification #


locally.show(title: title.text, message: message.text);

schedule notification #

locally.schedule(title: title.text, message: message.text, duration: Duration(seconds: 5));

Show a notification with a specified interval periodically #

locally.showPeriodically(title: title.text, message: message.text, repeatInterval: Repeat.Hourly);

Show a daily notification at a specific timely #

locally.showDailyAtTime(title: title.text, message: message.text, time: Time.hour);

Show a weekly notification on specific day and time #

locally.showWeeklyAtDayAndTime(title: title.text, message: message.text, time: Time.minute, day: Days.monday);

Retrieve pending notification requests #

locally.retrievePendingNotifications();

Cancelling/deleting a notification #

locally.cancel(0);

Cancelling/deleting all notification #

locally.cancelAll();

Get details on if the app was launched via a notification created by this plugin #

locally.getDetailsIfAppWasLaunchedViaNotification();

After installation in pubspec.yaml: you will need to carry out the following configuration on both platforms respectively

Android Configuration #

If your application needs the ability to schedule notifications then you need to request permissions to be notified when the phone has been booted as scheduled notifications uses the AlarmManager API to determine when notifications should be displayed. However, they are cleared when a phone has been turned off. Requesting permission requires adding the following to the manifest (i.e. your application's AndroidManifest.xml file)

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

The following is also needed to ensure scheduled notifications remain scheduled upon a reboot (this is handled by the plugin)

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

Developers will also need to add the following so that plugin can handle displaying scheduled notifications

<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />

If the vibration pattern of an Android notification will be customised then add the following

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

Here's and example of what your AndroidManifest.xml should look like here

Release build configuration #

When doing a release build of your app, which is the default setting when building an APK or app bundle, you'll likely need to customise your ProGuard configuration file as per this link and add the following line.

-keep class com.dexterous.** { *; }

After doing so, rules specific to the GSON dependency being used by the plugin will also needed to be added. These rules can be found here. The example app has a consolidated Proguard rules (proguard-rules.pro) file that combines these together for reference here.

You will also need to ensure that you have configured the resources that should be kept so that resources like your notification icons aren't discarded by the R8 compiler by following the instructions here. Without doing this, you might not see the icon you've specified in your app's notifications. The configuration used by the example app can be found here where it is specifying that all drawable resources should be kept, as well as the file used to play a custom notification sound (sound file is located here).

iOS integration #

General setup #

Add the following lines to the didFinishLaunchingWithOptions method in the AppDelegate.m/AppDelegate.swift file of your iOS project

Objective-C:

if (@available(iOS 10.0, *)) {
  [UNUserNotificationCenter currentNotificationCenter].delegate = (id<UNUserNotificationCenterDelegate>) self;
}

Swift:

if #available(iOS 10.0, *) {
  UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}

By design, iOS applications do not display notifications when they're in the foreground. For iOS 10+, use the presentation options to control the behaviour for when a notification is triggered while the app is in the foreground. For older versions of iOS, you need to handle the callback as part of specifying the method that should be fired to the onDidReceiveLocalNotification argument when creating an instance IOSInitializationSettings object that is passed to the function for initializing the plugin. A snippet below from the sample app shows how this can be done

If you have set notifications to be periodically shown, then on older iOS versions (< 10), if the application was uninstalled without cancelling all alarms then the next time it's installed you may see the "old" notifications being fired. If this is not the desired behaviour, then you can add code similar to the following to the didFinishLaunchingWithOptions method of your AppDelegate class.

Objective-C:

if(![[NSUserDefaults standardUserDefaults]objectForKey:@"Notification"]){
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"Notification"];
}

Swift:

if(!UserDefaults.standard.bool(forKey: "Notification")) {
    UIApplication.shared.cancelAllLocalNotifications()
    UserDefaults.standard.set(true, forKey: "Notification")
}

Custom notification sound restrictions #

When using custom notification sound, developers should be aware that iOS enforces restrictions on this (e.g. supported file formats). As of this writing, this is documented by Apple at

https://developer.apple.com/documentation/usernotifications/unnotificationsound?language=objc

Using firebase_messaging with flutter_local_notifications #

Previously, there were issue that prevented this plugin working properly with the firebase_messaging plugin. This meant that callbacks from each plugin might not be invoked. Version 6.0.13 of firebase_messaging should resolve this issue so please bump your firebase_messaging dependency and follow the steps covered in firebase_messaging's readme file.

Testing #

As the plugin class is not static, it is possible to mock and verify it's behaviour when writing tests as part of your application. Check the source code for a sample test suite can be found at test/flutter_local_notifications_test.dart that demonstrates how this can be done. If you decide to use the plugin class directly as part of your tests, note that the methods will be mostly a no-op and methods that return data will return default values. Part of this is because the plugin detects if you're running on a supported plugin to determine which platform implementation of the plugin should be used. If it's neither Android or iOS, then it defaults to the aforementioned behaviour to reduce friction when writing tests. If this not desired then consider using mocks. Note there is also a named constructor that can be used to pass the platform for the plugin to resolve the desired platform-specific implementation.

0.2.6+9 #

  • Added new co-author kmicatocorp@gmail.com

0.2.6+8 #

0.2.6+6 #

  • Created helper file with helper classes in it

  • Cleaned up Locally codebase

0.2.5+2 #

  • Commented on all Locally Method

  • Corrected some declarations

  • Added cancel method

  • Added cancelAll method

  • Added getDetailsIfAppWasLaunchedViaNotification method

0.2.0 #

  • Fixed Navigation Error

  • Added scheduleNotification

  • Added showPeriodically method

  • Added showDailyAtTime method

  • Added showWeeklyAtDayAndTime method

  • Added retrievePendingNotifications method

0.1.0+1 #

  • Changed Navigation rules in locally class

0.0.6+3 #

  • Removed an error causing function in Locally

0.0.5 #

  • Added a better CHANGELOG.md file.

0.0.4 #

  • I removed ImageProvider as it was not useful in the class.

  • Added a comprehensive BSD LICENSE

0.0.3 #

  • Fix a bug , I discovered that appIcon had to be required, initially it had a default value, which kept throwing an error.

  • Deleted send_screen.dart from Example project

0.0.2 #

  • Few changes were made in Locally class.

  • Example project was added the repository

0.0.1 #

  • Locally is release, works pretty basic, you just have to write Locally(title: 'Hello Samuel', message: 'New message for you').show().

example/lib/main.dart

import 'package:example/second_screen.dart';
import 'package:flutter/material.dart';
import 'package:locally/locally.dart';

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

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Locally Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Locally Example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {

  var _formKey = GlobalKey<FormState>();
  TextEditingController title = TextEditingController();
  TextEditingController message = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  showMessage() {
    if(_formKey.currentState.validate()) {
      _formKey.currentState.save();
      Locally locally;

      locally = Locally(
          context: context,
          payload: 'test',
          pageRoute: MaterialPageRoute(builder: (context) => SecondScreen(title: title.text, message: message.text)),
          appIcon: 'mipmap/ic_launcher',
      );
      locally.show(title: title.text, message: message.text);

    }
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          showMessage();
        },
      ),
      body: Center(

        child: Form(
          key: _formKey,
          child: Column(

            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[

              Container(
                margin: EdgeInsets.all(20),
                child: TextFormField(
                  controller: title,
                  validator: (v){
                    return v.isEmpty ? 'Enter title' : null;
                  },
                  decoration: InputDecoration(
                      hintText: 'Title',
                      labelText: 'Title'
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.all(20),
                child: TextFormField(
                  controller: message,
                  validator: (v){
                    return v.isEmpty ? 'Enter message body' : null;
                  },
                  decoration: InputDecoration(
                      hintText: 'Message',
                      labelText: 'Message'
                  ),
                ),
              ),

            ],
          ),
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  locally: ^0.2.6+9

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

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

3. Import it

Now in your Dart code, you can use:


import 'package:locally/locally.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
68
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
84
Learn more about scoring.

We analyzed this package on Jul 12, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.14
  • Flutter: 1.17.5

Analysis suggestions

Package does not support Flutter platform linux

Because:

  • package:locally/locally.dart that imports:
  • package:flutter_local_notifications/flutter_local_notifications.dart that declares support for platforms: android, ios

Package does not support Flutter platform macos

Because:

  • package:locally/locally.dart that imports:
  • package:flutter_local_notifications/flutter_local_notifications.dart that declares support for platforms: android, ios

Package does not support Flutter platform web

Because:

  • package:locally/locally.dart that imports:
  • package:flutter_local_notifications/flutter_local_notifications.dart that declares support for platforms: android, ios

Package does not support Flutter platform windows

Because:

  • package:locally/locally.dart that imports:
  • package:flutter_local_notifications/flutter_local_notifications.dart that declares support for platforms: android, ios

Package not compatible with SDK dart

Because:

  • locally that is a package requiring null.

Health suggestions

Format lib/locally.dart.

Run flutter format to format lib/locally.dart.

Format lib/src/helpers.dart.

Run flutter format to format lib/src/helpers.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
flutter_local_notifications ^1.4.1 1.4.4+2 1.5.0-beta.6
Transitive dependencies
collection 1.14.12 1.14.13
flutter_local_notifications_platform_interface 1.0.1 2.0.0-beta.1
meta 1.1.8 1.2.2
platform 2.2.1
plugin_platform_interface 1.0.2
sky_engine 0.0.99
typed_data 1.1.6 1.2.0
vector_math 2.0.8 2.1.0-nullsafety
Dev dependencies
flutter_test