OneSignal-Flutter-SDK icon indicating copy to clipboard operation
OneSignal-Flutter-SDK copied to clipboard

setSubscriptionObserver never fires

Open Lomski opened this issue 5 years ago • 11 comments

Description:

setSubscriptionObserver doesnt fires on first app start.

Environment

flutter doctor
[✓] Flutter (Channel stable, 2.2.1, on Linux, locale ru_RU.UTF-8)
    • Flutter version 2.2.1 at /home/user/Programs/flutter
    • Framework revision 02c026b03c (13 days ago), 2021-05-27 12:24:44 -0700
    • Engine revision 0fdb562ac8
    • Dart version 2.13.1

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    • Android SDK at /home/user/Android/Sdk
    • Platform android-30, build-tools 29.0.2
    • ANDROID_HOME = /home/user/Android/Sdk
    • Java binary at: /home/user/.local/share/JetBrains/Toolbox/apps/AndroidStudio/ch-0/193.6626763/jre/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • Chrome at google-chrome

[✓] Android Studio (version 4.0)
    • Android Studio at /home/user/.local/share/JetBrains/Toolbox/apps/AndroidStudio/ch-0/193.6626763
    • Flutter plugin version 51.0.1
    • Dart plugin version 193.7547
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)

[✓] Connected device (3 available)
    • ONEPLUS A6010 (mobile)       • e29b8f89      • android-arm64  • Android 10 (API 29)
    • AOSP on IA Emulator (mobile) • emulator-5554 • android-x86    • Android 9 (API 28) (emulator)
    • Chrome (web)                 • chrome        • web-javascript • Google Chrome 81.0.4044.138

• No issues found!

Steps to Reproduce Issue:

  1. Create new flutter app
  2. add onesignal to pubspec
  3. Start app
code
Limport 'package:flutter/material.dart';
import 'package:onesignal_flutter/onesignal_flutter.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  // This widget is the root of your application.
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  initPlatformState() {
    if (!mounted) return;

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

    // NOTE: Replace with your own app ID from https://www.onesignal.com
    OneSignal.shared.setAppId('ONESIGNAL_APP_ID');

    OneSignal.shared.setSubscriptionObserver((OSSubscriptionStateChanges changes) {
      print('--------------------------------');
      print(changes.to.userId);
      print('--------------------------------');
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

pubspec
name: flutter_app2
description: A new Flutter application.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  onesignal_flutter: ^3.0.0
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

With 2+ onesignal versions it works fine. It broke in version 3.0.0 (and beta versions). Also looks like device actually registered besause i see this in onesignal logs.

D/OneSignal( 5194): OneSignalRestClient: POST RECEIVED JSON: {"success":true,"id":"b2e1ca2f-bfc0-4cdc-8f84-b4f1356f9b98"}
D/OneSignal( 5194): doCreateOrNewSession:response: {"success":true,"id":"b2e1ca2f-bfc0-4cdc-8f84-b4f1356f9b98"}
I/OneSignal( 5194): Device registered, UserId = b2e1ca2f-bfc0-4cdc-8f84-b4f1356f9b98

Lomski avatar Jun 10 '21 05:06 Lomski

Did you manage to solve this ?

ImranKaagga avatar Jul 01 '21 06:07 ImranKaagga

Having the same issue, fired 1x after that never fires

marclester-tang avatar Jul 02 '21 11:07 marclester-tang

Any updates on this? Is it related to https://github.com/OneSignal/OneSignal-Android-SDK/issues/749?

Lomski avatar Aug 09 '21 06:08 Lomski

@Lomski Does it fire the first time ever installing the app and subscribing or does it never fire at all? On subsequent App starts the observer will not fire unless the status has changed since the previous session

emawby avatar Aug 10 '21 21:08 emawby

@emawby Installing app. This print never fires:

OneSignal.shared.setSubscriptionObserver((OSSubscriptionStateChanges changes) {
  print(changes.to.userId);
});

This print return null:

var status = await OneSignal.shared.getDeviceState();

print(status?.userId);

After that i see in console this:

D/OneSignal( 9289): OneSignalRestClient: POST RECEIVED JSON: {"success":true,"id":"8c611e7e-86ba-422a-8095-68ed536e83a8"}
D/OneSignal( 9289): doCreateOrNewSession:response: {"success":true,"id":"8c611e7e-86ba-422a-8095-68ed536e83a8"}
I/OneSignal( 9289): Device registered, UserId = 8c611e7e-86ba-422a-8095-68ed536e83a8
After that in onesignal app appears new user:

Снимок экрана от 2021-08-12 15-05-27

So it looks like setSubscriptionObserver doesnt work. With onesignal versions before null safety (2+) it works.

Test this with my app and just created new flutter project on a real device and emulator.

Lomski avatar Aug 12 '21 05:08 Lomski

Hi @Lomski, this looks like a bug on our end. A fix is being implemented!

Best, Nan

nan-li avatar Aug 14 '21 01:08 nan-li

Hi @nan-li any update on this issue?

muhammadsaddamnur avatar Aug 19 '21 03:08 muhammadsaddamnur

Hi @muhammadsaddamnur, this should be fixed in the next Flutter SDK release. Thanks for your patience, ~ Nan

nan-li avatar Aug 19 '21 16:08 nan-li

@nan-li please let us know when the issue is fixed please!!!!

pabloIO avatar Aug 21 '21 19:08 pabloIO

Tested this merge. Looks like setSubscriptionObserver works now. Waiting for release.

Lomski avatar Aug 24 '21 06:08 Lomski

Hi all, thanks for your patience. The Flutter 3.2.1 Release is available.

nan-li avatar Aug 24 '21 21:08 nan-li