flutterpush-notificationonesignal

How to get OneSignal playerId (userId) in Flutter?


How to get playerId of a user inside the flutter app?. Player Id can be found in One signal website but i want that inside the flutter app and want to store it to send the notification to particular user.


Solution

  • This is my goto function for initating onesignal

      Future<void> initOneSignal(BuildContext context) async {
        /// Set App Id.
        await OneSignal.shared.setAppId(SahityaOneSignalCollection.appID);
    
        /// Get the Onesignal userId and update that into the firebase.
        /// So, that it can be used to send Notifications to users later.̥
        final status = await OneSignal.shared.getDeviceState();
        final String? osUserID = status?.userId;
        // We will update this once he logged in and goes to dashboard.
        ////updateUserProfile(osUserID);
        // Store it into shared prefs, So that later we can use it.
        Preferences.setOnesignalUserId(osUserID);
    
        // The promptForPushNotificationsWithUserResponse function will show the iOS push notification prompt. We recommend removing the following code and instead using an In-App Message to prompt for notification permission
        await OneSignal.shared.promptUserForPushNotificationPermission(
          fallbackToSettings: true,
        );
    
        /// Calls when foreground notification arrives.
        OneSignal.shared.setNotificationWillShowInForegroundHandler(
          handleForegroundNotifications,
        );
    
        /// Calls when the notification opens the app.
        OneSignal.shared.setNotificationOpenedHandler(handleBackgroundNotification);
      }