onesignal 0.0.1

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

OneSignal Flutter SDK Build Status


OneSignal is a free push notification service for mobile apps. This SDK makes it easy to integrate your Flutter iOS and/or Android apps with OneSignal.

alt text

Installation #

See the Setup Guide for setup instructions.

Change Log #

See this repository's release tags for a complete change log of every released version.

Support #

Please visit this repository's Github issue tracker for feature requests and bug reports related specificly to the SDK. For account issues and support please contact OneSignal support from the OneSignal.com dashboard.

Demo Project #

To make things easier, we have published a demo project in the /example folder of this repository.

Supports: #

  • Tested from iOS 8 to iOS 11.3
  • Tested from Android 4.0.3 (API level 15) to Android 8.1 (27)

0.0.1 #

  • TODO: Describe initial release.

example/lib/main.dart

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

//import OneSignal
import 'package:onesignal/onesignal.dart';

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

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

class _MyAppState extends State<MyApp> {
  String _debugLabelString = "";
  String _emailAddress;
  bool _enableConsentButton = false;

  // CHANGE THIS parameter to true if you want to test GDPR privacy consent
  bool _requireConsent = true;

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

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    if (!mounted) return;

    OneSignal.shared.setLogLevel(OSLogLevel.verbose, OSLogLevel.none);

    OneSignal.shared.setRequiresUserPrivacyConsent(_requireConsent);

    var settings = { 
      OSiOSSettings.autoPrompt : false,
      OSiOSSettings.promptBeforeOpeningPushUrl : true 
    };

    await OneSignal.shared.init("78e8aff3-7ce2-401f-9da0-2d41f287ebaf", iOSSettings: settings);
    
    OneSignal.shared.setSubscription(true);

    OneSignal.shared.setNotificationReceivedHandler((notification) {
      print("Main received notidication");
      this.setState(() {
        _debugLabelString = "Received notification: \n${notification.jsonRepresentation().replaceAll("\\n", "\n")}";
      });
    });
    
    OneSignal.shared.setNotificationOpenedHandler((OSNotificationOpenedResult result) {
      this.setState(() {
        _debugLabelString = "Opened notification: \n${result.notification.jsonRepresentation().replaceAll("\\n", "\n")}";
      });
    });

    OneSignal.shared.setSubscriptionObserver((OSSubscriptionStateChanges changes) {
      print("SUBSCRIPTION STATE CHANGED: ${changes.jsonRepresentation()}");
    });

    OneSignal.shared.setPermissionObserver((OSPermissionStateChanges changes) {
      print("PERMISSION STATE CHANGED: ${changes.jsonRepresentation()}");
    });

    OneSignal.shared.setEmailSubscriptionObserver((OSEmailSubscriptionStateChanges changes) {
      print("EMAIL SUBSCRIPTION STATE CHANGED ${changes.jsonRepresentation()}");
    });

    OneSignal.shared.setInFocusDisplayType(OSNotificationDisplayType.notification);

    bool requiresConsent = await OneSignal.shared.requiresUserPrivacyConsent();

    this.setState(() {
      _enableConsentButton = requiresConsent;
    });
  }

  void _handleGetTags() {
    OneSignal.shared.getTags().then((tags) {
      if (tags == null) return;
      setState((() {
        _debugLabelString = "$tags";
      }));
    }).catchError((error) {
      setState(() {
        _debugLabelString = "$error";
      });
    });
  }

  void _handleSendTags() {
    print("Sending tags");
    OneSignal.shared.sendTag("test2", "val2").then((response) {
      print("Successfully sent tags with response: $response");
    }).catchError((error) {
      print("Encountered an error sending tags: $error");
    });
  }

  void _handlePromptForPushPermission() {
    print("Prompting for Permission");
    OneSignal.shared.promptUserForPushNotificationPermission().then((accepted) {
      print("Accepted permission: $accepted");
    });
  }

  void _handleGetPermissionSubscriptionState() {
    print("Getting permissionSubscriptionState");
    OneSignal.shared.getPermissionSubscriptionState().then((status) {
      this.setState(() {
        _debugLabelString = status.jsonRepresentation();
      });
    });
  }

  void _handleSetEmail() {
    if (_emailAddress == null) return;

    print("Setting email");

    OneSignal.shared.setEmail(email: _emailAddress).whenComplete(() {
      print("Successfully set email");
    }).catchError((error) {
      print("Failed to set email with error: $error");
    });
  }

  void _handleLogoutEmail() {
    print("Logging out of email");
    OneSignal.shared.logoutEmail().then((v) {
      print("Successfully logged out of email");
    }).catchError((error) {
      print("Failed to log out of email: $error");
    });
  }

  void _handleConsent() {
    print("Setting consent to true");
    OneSignal.shared.consentGranted(true);

    print("Setting state");
    this.setState(() {
      _enableConsentButton = false;
    });
  }

  void _handleSetLocationShared() {
    print("Setting location shared to true");
    OneSignal.shared.setLocationShared(true);
  }

  void _handleDeleteTag() {
    print("Deleting tag");
    OneSignal.shared.deleteTag("test2").then((response) {
      print("Successfully deleted tags with response $response");
    }).catchError((error) {
      print("Encountered error deleting tag: $error");
    });
  }

  void _handleSendNotification() async {
    var status = await OneSignal.shared.getPermissionSubscriptionState();

    var playerId = status.subscriptionStatus.userId;

    var imgUrlString = "http://cdn1-www.dogtime.com/assets/uploads/gallery/30-impossibly-cute-puppies/impossibly-cute-puppy-2.jpg";

    var notification = OSCreateNotification(
      playerIds: [playerId],
      content: "this is a test from OneSignal's Flutter SDK",
      heading: "Test Notification",
      iosAttachments: {"id1" : imgUrlString},
      bigPicture: imgUrlString,
      buttons: [
        OSActionButton(text: "test1", id: "id1"),
        OSActionButton(text: "test2", id: "id2")
      ]
    );
    
    var response = await OneSignal.shared.postNotification(notification);
    
    this.setState(() {
      _debugLabelString = "Sent notification with response: $response";
    });
  }

  void _handleSendSilentNotification() async {
    var status = await OneSignal.shared.getPermissionSubscriptionState();

    var playerId = status.subscriptionStatus.userId;

    var notification = OSCreateNotification.silentNotification(
      playerIds: [playerId],
      additionalData: {
        'test' : 'value'
      }
    );
    
    var response = await OneSignal.shared.postNotification(notification);

    this.setState(() {
      _debugLabelString = "Sent notification with response: $response";
    });
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('OneSignal Flutter Demo'),
          backgroundColor: Color.fromARGB(255, 212, 86, 83),
        ),
        body: Container(
          padding: EdgeInsets.all(10.0),
          child: SingleChildScrollView(
            child: new Table(
              children: [
                new TableRow(
                  children: [
                    new OneSignalButton("Get Tags", _handleGetTags, !_enableConsentButton)
                  ]
                ),
                new TableRow(
                  children: [
                    new OneSignalButton("Send Tags", _handleSendTags, !_enableConsentButton)
                  ]
                ),
                new TableRow(
                  children: [
                    new OneSignalButton("Prompt for Push Permission", _handlePromptForPushPermission, !_enableConsentButton)
                  ]
                ),
                new TableRow(
                  children: [
                    new OneSignalButton("Print Permission Subscription State", _handleGetPermissionSubscriptionState, !_enableConsentButton)
                  ]
                ),
                new TableRow(
                  children: [
                    new TextField(
                      textAlign: TextAlign.center,
                      decoration: InputDecoration(
                        hintText: "Email Address",
                        labelStyle: TextStyle(
                          color: Color.fromARGB(255, 212, 86, 83),
                        )
                      ),
                      onChanged: (text) {
                        this.setState(() {
                          _emailAddress = text == "" ? null : text;
                        });
                      },
                    )
                  ]
                ),
                new TableRow(
                  children: [
                    Container(
                      height: 8.0,
                    )
                  ]
                ),
                new TableRow(
                  children: [
                    new OneSignalButton("Set Email", _handleSetEmail, !_enableConsentButton)
                  ]
                ),
                new TableRow(
                  children: [
                    new OneSignalButton("Logout Email", _handleLogoutEmail, !_enableConsentButton)
                  ]
                ),
                new TableRow(
                  children: [
                    new OneSignalButton("Provide GDPR Consent", _handleConsent, _enableConsentButton)
                  ]
                ),
                new TableRow(
                  children: [
                    new OneSignalButton("Set Location Shared", _handleSetLocationShared, !_enableConsentButton)
                  ]
                ),
                new TableRow(
                  children: [
                    new OneSignalButton("Delete Tag", _handleDeleteTag, !_enableConsentButton)
                  ]
                ),
                new TableRow(
                  children: [
                    new OneSignalButton("Post Notification", _handleSendNotification, !_enableConsentButton)
                  ]
                ),
                new TableRow(
                  children: [
                    new OneSignalButton("Post Silent Notification", _handleSendSilentNotification, !_enableConsentButton)
                  ]
                ),
                new TableRow(
                  children: [
                    new Container(
                      child: new Text(_debugLabelString),
                      alignment: Alignment.center,
                    )
                  ]
                )
              ],
            ),
          ),
        )
      ),
    );
  }
}

typedef void OnButtonPressed();

class OneSignalButton extends StatefulWidget {
  final String title;
  final OnButtonPressed onPressed;
  final bool enabled;

  OneSignalButton(this.title, this.onPressed, this.enabled);

  State<StatefulWidget> createState() => new OneSignalButtonState();
}

class OneSignalButtonState extends State<OneSignalButton> {
  @override
    Widget build(BuildContext context) {
      // TODO: implement build
      return new Table(
        children: [
          new TableRow(
            children: [
              new FlatButton(
                disabledColor: Color.fromARGB(180, 212, 86, 83),
                disabledTextColor: Colors.white,
                color: Color.fromARGB(255, 212, 86, 83),
                textColor: Colors.white,
                padding: EdgeInsets.all(8.0),
                child: new Text(widget.title),
                onPressed: widget.enabled ? widget.onPressed : null,
              )
            ]
          ),
          new TableRow(
            children: [
              Container(
                height: 8.0,
              )
            ]
          ),
        ],
      );
    }
}

Use this package as a library

1. Depend on it

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


dependencies:
  onesignal: ^0.0.1

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter packages get

Alternatively, your editor might support pub get or 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:onesignal/onesignal.dart';
  
Version Uploaded Documentation Archive
1.1.0 Mar 11, 2019 Go to the documentation of onesignal 1.1.0 Download onesignal 1.1.0 archive
1.0.5 Jan 17, 2019 Go to the documentation of onesignal 1.0.5 Download onesignal 1.0.5 archive
1.0.4 Jan 10, 2019 Go to the documentation of onesignal 1.0.4 Download onesignal 1.0.4 archive
1.0.3 Nov 5, 2018 Go to the documentation of onesignal 1.0.3 Download onesignal 1.0.3 archive
1.0.2 Sep 12, 2018 Go to the documentation of onesignal 1.0.2 Download onesignal 1.0.2 archive
1.0.1 Aug 1, 2018 Go to the documentation of onesignal 1.0.1 Download onesignal 1.0.1 archive
1.0.0 Aug 1, 2018 Go to the documentation of onesignal 1.0.0 Download onesignal 1.0.0 archive
0.0.1 Jul 30, 2018 Go to the documentation of onesignal 0.0.1 Download onesignal 0.0.1 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
95
Health:
Code health derived from static analysis. [more]
--
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
--
Overall:
Weighted score of the above. [more]
47
Learn more about scoring.

The package version is not analyzed, because it does not support Dart 2. Until this is resolved, the package will receive a health and maintenance score of 0.

Analysis issues and suggestions

Support Dart 2 in pubspec.yaml.

The SDK constraint in pubspec.yaml doesn't allow the Dart 2.0.0 release. For information about upgrading it to be Dart 2 compatible, please see https://dart.dev/dart-2#migration.

Maintenance issues and suggestions

Make sure dartdoc successfully runs on your package's source files. (-10 points)

Dependencies were not resolved.