How to get userId from Onsignal Flutter on App start?

Viewed 32

I am facting an issue related to OneSignal response user-id: null on App start. I want to get device state on Application Running on main flutter.

Is there any posibile way to acheived this, please kindly give me the advice. Thank you!!

Note The issue only when first install

void main() async {
  var widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
  FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
  await Firebase.initializeApp();
  await _initController();
  initNotification();
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  runApp(const TLCustomerApp());
  ErrorWidget.builder = (FlutterErrorDetails details) => const Scaffold(
        body: Center(
          child: ListTile(
            minLeadingWidth: 10,
            leading: Icon(Icons.error_outline),
            title: Text("There is something went wrong,\n please try again!"),
          ),
        ),
      );
  FlutterNativeSplash.remove();
}


void initNotification() async {
  OneSignal.shared.setAppId(oneSignalKey);
  final status = await OneSignal.shared.getDeviceState();
  final String? osUserID = status?.userId;
  print("==>SUBSCRIBE_ID:${osUserID}");
  OneSignal.shared.setNotificationWillShowInForegroundHandler((OSNotificationReceivedEvent event) {event.complete(event.notification);
  });
  OneSignal.shared.setNotificationOpenedHandler((OSNotificationOpenedResult result) {
    var data = result.notification.additionalData;
    // if (data != null) {
    //   var routeName = data["routeName"];
    //   Get.toNamed(routeName);
    // }
  });
  OneSignal.shared.setPermissionObserver((OSPermissionStateChanges changes) {});
  OneSignal.shared
      .setSubscriptionObserver((OSSubscriptionStateChanges changes) {});
  OneSignal.shared.setEmailSubscriptionObserver(
      (OSEmailSubscriptionStateChanges emailChanges) {});
}
1 Answers

Please add this in your code and you get onesignal user"userId".

 OneSignal.shared.setSubscriptionObserver((OSSubscriptionStateChanges changes) {
    //  print(changes.to.userId);
   String? userId = changes.to.userId ?? '';
   if (userId != '') {
     registerUserId(userId);
   }
 });
Related