Push Notification Delivery To Specific User in Flutter with OneSignal python Solved by komal swami - June 20, 2024June 20, 20240 Contents Introduction In today’s mobile-first world, push notifications are essential for user engagement. However, managing push notifications across multiple devices and sessions can be challenging. In this blog post, we’ll explore a common issue where users do not receive notifications after logging out and logging back in, especially on different devices or accounts. To ensure seamless notification delivery, we’ll share a comprehensive solution using OneSignal, Flutter, and Django REST API. The Problem We encountered a significant issue where users were not receiving notifications consistently. Specifically, the problem arose when users logged out and logged in again on different devices or with other accounts. This inconsistency led to a poor user experience and reduced engagement. Root Cause AnalysisThe primary issue was the improper handling of OneSignal’s external IDs and session management. Without a stable identifier and proper lifecycle management, OneSignal couldn’t reliably target the correct devices for notifications. Additionally, we had to update the onesignal_flutter package to the latest version to ensure compatibility and proper functionality. The SolutionTo address this, we implemented a robust approach involving: Using a Stable Identifier: We used each user’s UUID as the OneSignal external ID. Proper Logout Handling: Clearing the external ID on logout to prevent notifications from being sent to the wrong user. Consistent Login Management: Setting the external ID appropriately during login to ensure notifications reach the correct devices. Updating the Package: Ensuring we used the latest version of the onesignal_flutter package to leverage the latest features and fixes. OneSignal Notification Lifecycle Understanding the lifecycle of OneSignal notifications is crucial for managing subscriptions and ensuring reliable delivery: Logging In: When a user logs in, the external ID is set using their UUID. This ensures that all notifications are correctly targeted to this user. Logging Out: When a user logs out, the external ID is cleared, preventing notifications from being sent to the wrong user. Re-Logging In: When a user logs back in on a different device or with a different account, the external ID is set again, ensuring notifications are correctly routed. So what is external ID in OneSignal – The external_id is OneSignal’s default and recommended alias label. This should be the main identifier you use to identify users. It is set when calling the OneSignal. Implementation Steps : Following example steps are for OneSignal send notification to specific user Step 1: Setting Up OneSignal in Flutter First, integrate OneSignal into your Flutter project. run the following commands in your project directory. flutter pub add permission_handlerflutter pub add onesignal_flutter Step 2: Setting Up OneSignal in FlutterInitialize OneSignal in your main Dart file: Future main() async {WidgetsFlutterBinding.ensureInitialized();// NOTE: Replace with your own app ID from https://www.onesignal.com// OneSignal.initialize("77e32082-ea27-42e3-a898-c72e141824ef");OneSignal.Notifications.requestPermission(true); //request permission for sending notification runApp(const MyApp());} Step 4: Logging In Users When users log in, set the external ID: void onLoginSuccess(String userUuid) {setExternalId(userUuid);} write your send notification logic : Future _incrementCounter() async {var user_id = "user8766554";OneSignal.login(user_id!);final String oneSignalAppId = 'ONE_SIGNAL_ID';final String restApiKey = 'REST_API_KEY';final companyName = "COMPANY_NAME";final Map notification = {'app_id': oneSignalAppId,'include_external_user_ids':[user_id],'headings': {'en': 'Notification'},'contents': {'en': 'Hello World!'},'priority':2};// Send the notification using OneSignal's REST APIfinal Uri url = Uri.parse('https://onesignal.com/api/v1/notifications');final http.Response response = await http.post(url,headers: {'Content-Type': 'application/json','Authorization': 'Basic $restApiKey',},body: json.encode(notification),);if (response.statusCode == 200) {print('Notification sent successfully');} else {print('Failed to send notification. Status code: ${response.statusCode}');print('Response body: ${response.body}');}setState(() {_counter++;}); } step 5 logging out : OneSignal.logout(); Benefits of This Approach Consistency: Ensures notifications are consistently sent to the correct devices. Scalability: Manages multiple devices and sessions seamlessly. User Experience: Improves user engagement by ensuring they receive timely notifications. Conclusion By implementing this approach during our development phase, we resolved the notification delivery issues and enhanced the user experience. Using OneSignal with a stable identifier and proper session management in Flutter and Django REST API, we ensured that users receive notifications consistently, regardless of their login or device usage patterns. This method guarantees that users stay engaged and informed, leading to a better overall user experience. Following this guide and integrating the sample code provided will help you ensure reliable notification delivery for your users across multiple devices and sessions. Happy coding! and hope you have enjoyed reading Push Notification Delivery To Specific User in Flutter with OneSignal. Share this:Click to share on Twitter (Opens in new window)Click to share on Facebook (Opens in new window)MoreClick to share on LinkedIn (Opens in new window)Click to share on WhatsApp (Opens in new window)Click to email a link to a friend (Opens in new window)Like this:Like Loading... Related