flutter_one_signal 0.2.1

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

flutter_one_signal

pub package

Current Features

Current features available:

  • Sign up for push notifications
  • Send a user tag
  • Set email
  • Logout email
  • Get user id
  • Set subscription
  • Handle notification receive/open events with notification as an input

Android Setup

Just follow these steps, and ignore all the native instructions from both Firebase and One Signal, a big chunk of that boilerplate code is handled by this plugin

Create a One Signal, Firebase projects

Open android/app/src/main/AndroidManifest.xml and copy package value

Open Firebase console/Project Settings, add Android app and paste package copied before into Android package name

Click Register app in the next step download google-services.json and paste in in android/app

Now, add an Android app in One Signal using Server key and Sender ID from Firebase Project Settings/Cloud messaging

Next, add this code to android/app/src/build.gradle, replacing APP_ID with your One Signal App ID

android {
   defaultConfig {
      ...
      manifestPlaceholders = [
          onesignal_app_id: 'APP_ID',
          onesignal_google_project_number: 'REMOTE'
      ]
    }
 }

iOS Setup

Open ios directory in Xcode and copy Bundle identifier

Now open FIrebase console, add an iOS app for your project using that Bundle ID and download GoogleService-info.plist from the next step. Click continue for the next steps, just ignore them

Open Xcode and paste GoogleService-info.plist into Runner directory, the one that has AppDelegate file in it

It's important that you paste it using Xcode, if you use just a file explorer there will be some missing setting that I think Xcode does for you and your app won't work

Now go to the General tab and make sure you have Automatically manage signing on and select your profile, this is going to save you from taking an extra step

If you don't have an Apple developer profile - set it up first

Next open Capabilities tab and turn Push Notifications on

And Background Modes with Remote notifications checkbox

Next, generate a .p12 file for your app using this tool, download it and keep the password

Add iOS app is One Signal/Settings and upload .p12 file and the password that you get before

Flutter Part

To use this plugin, add flutter_one_signal as a dependency in your pubspec.yaml file.

And this code anywhere where you want to initialize One Signal push notifications in your app

var notificationsPermissionGranted = await FlutterOneSignal.startInit(
     appId: 'ONE_SIGNAL_APP_ID',
     inFocusDisplaying: OSInFocusDisplayOption.InAppAlert,
     notificationReceivedHandler: (notification) {
       print('received : $notification');
     },
     notificationOpenedHandler: (notification) {
       print('opened : $notification');
     },
     unsubscribeWhenNotificationsAreDisabled: false,
     );

print('Push notification permission granted $notificationsPermissionGranted');

FlutterOneSignal.sendTag('userId', 'demoUserId');

FlutterOneSignal.setEmail('email');

FlutterOneSignal.logoutEmail();

FlutterOneSignal.setSubscription(false);

var userId = await FlutterOneSignal.getUserId();
print("Received $userId");

startInit method signs you up for notifications and you pass notificationReceivedHandler, notificationOpenedHandler just like in the native SDK's

The only required attribute here is appId. inFocusDisplaying by default is InAppAlert, unsubscribeWhenNotificationsAreDisabled works only on Android, it's false by default

You could've noticed that I have a duplicated way of declaring One Signal app id. This is due to a very different iOS/Android setup logic. So, for now, you have to include it in build.gradle file. In the next iterations, I'll try to  get rid of this part

On Android startInit returns Future of true instantaneously

Notification Open Handler

By default you have your home page opened when notification is clicked. This is not a behavior you'd want for a real app. To disable this behavior on Android add this code to android/app/src/main/AndroidManifest.xml

<application
    ...>
    ...                                                                                      
    <meta-data android:name="com.onesignal.NotificationOpened.DEFAULT" android:value="DISABLE" />  
</application>

And now you can open the screen you want in Flutter

FlutterOneSignal.startInit(                                             
    ...             
    notificationOpenedHandler: (notification) {                                            
      Navigator.of(context).pushNamed('somePage');                       
    },                                                                  
);

I haven't figured out an iOS fix to disable the default open behavior. You can still use the Flutter logic, it's just that your initial page will appear before the intended one

TODO

  • [ ] Privacy section
  • [ ] Post notification

0.2.1

  • getUserId returns null on initial call fix

0.2.0

  • Logout email, setSubscription

0.1.2

  • Set email Android fix

0.1.1

  • Set email

0.1.0

  • Initial release

example/lib/main.dart

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Home(title: 'Flutter One Signal'),
      routes: {
        'pageTwo': (context) => PageTwo(title: 'Page Two'),
      },
    );
  }
}

class Home extends StatefulWidget {
  final String title;

  Home({Key key, this.title}) : super(key: key);

  @override
  _HomeState createState() => new _HomeState();
}

class _HomeState extends State<Home> {
  static const String DEFAULT_APP_ID = '50c236d4-8355-451d-a140-3adf38b04c43';
  static const String TEST_APP_ID = '5e92b9ef-1336-4ca8-8357-7c8e3dd92e9c';

  @override
  void initState() {
    super.initState();
    _initOneSignal();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Align(
            alignment: Alignment.center,
            child: RaisedButton(
              onPressed: _unsubscribe,
              child: Text('Unsubscrbe'),
            ),
          ),
          SizedBox(height: 16.0),
          Align(
            alignment: Alignment.center,
            child: RaisedButton(
              onPressed: _logoutEmail,
              child: Text('Logout email'),
            ),
          )
        ],
      ),
    );
  }

  _initOneSignal() async {
    var notificationsPermissionGranted = await FlutterOneSignal.startInit(
        appId: DEFAULT_APP_ID,
        // todo Replace with your own, this won't work for you
        notificationOpenedHandler: (notification) {
          print('opened notification: $notification');
          Navigator.of(context).pushNamed('pageTwo');
        },
        notificationReceivedHandler: (notification) {
          print('received notification: $notification');
        });
    print(
        'Push notification permission granted $notificationsPermissionGranted');

    FlutterOneSignal.sendTag('userId', 'demoUserId');

//    FlutterOneSignal.setEmail('name@email.com');

    var userId = await FlutterOneSignal.getUserId();
    print("User id : $userId");
  }

  _logoutEmail() {
    FlutterOneSignal.logoutEmail();
  }

  _unsubscribe() {
    FlutterOneSignal.setSubscription(false);
  }
}

class PageTwo extends StatefulWidget {
  final String title;

  PageTwo({Key key, this.title}) : super(key: key);

  @override
  _PageTwoState createState() => new _PageTwoState();
}

class _PageTwoState extends State<PageTwo> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Text('Page two'),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  flutter_one_signal: ^0.2.1

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:flutter_one_signal/flutter_one_signal.dart';
  
Version Uploaded Documentation Archive
0.2.1 Jun 27, 2018 Go to the documentation of flutter_one_signal 0.2.1 Download flutter_one_signal 0.2.1 archive
0.2.0 Jun 26, 2018 Go to the documentation of flutter_one_signal 0.2.0 Download flutter_one_signal 0.2.0 archive
0.1.2 Jun 25, 2018 Go to the documentation of flutter_one_signal 0.1.2 Download flutter_one_signal 0.1.2 archive
0.1.1 Jun 24, 2018 Go to the documentation of flutter_one_signal 0.1.1 Download flutter_one_signal 0.1.1 archive
0.1.0 Jun 24, 2018 Go to the documentation of flutter_one_signal 0.1.0 Download flutter_one_signal 0.1.0 archive
0.0.1 Jun 24, 2018 Go to the documentation of flutter_one_signal 0.0.1 Download flutter_one_signal 0.0.1 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
67
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
80
Overall:
Weighted score of the above. [more]
80
Learn more about scoring.

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

  • Dart: 2.0.0
  • pana: 0.12.3
  • Flutter: 0.8.4

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Suggestions

The description is too short.

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

Format lib/generated/i18n.dart.

Run flutter format to format lib/generated/i18n.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.28.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11
meta 1.1.6
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8