Flutter OneSignal example snipcode

SDK: https://documentation.onesignal.com/docs/flutter-sdk

Github: https://github.com/OneSignal/OneSignal-Flutter-SDK

Sample code

import 'dart:async';

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

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

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

class _MyAppState extends State<MyApp> {
  String _debugLabelString = "";

  @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);

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

    OneSignal.shared
        .setNotificationReceivedHandler((OSNotification notification) {
      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")}";
      });
    });

    // NOTE: Replace with your own app ID from https://www.onesignal.com
    await OneSignal.shared
        .init("39cfa80a-2a93-4765-a6e2-adaaaca4a79b", iOSSettings: settings);

    OneSignal.shared
        .setInFocusDisplayType(OSNotificationDisplayType.notification);
  }

  @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: new Container(
          child: new Text(_debugLabelString),
          alignment: Alignment.center,
        ),
      ),
    );
  }
}

Get player id

OneSignal.shared.getPermissionSubscriptionState().then((response) {
    String playerId = response.subscriptionStatus.userId.toString();

});

Remember user OneSignal.shared instead of OneSignal()

Leave a Reply

Your email address will not be published.Required fields are marked *