Implement OneSignal in Flutter

CodeWithFlutter
2 Min Read

OneSignal is a popular push notification service that you can use in your Flutter app to send notifications to your users. Here’s a high-level overview of how to integrate OneSignal into your Flutter app:

  1. Create a OneSignal account and set up a new app.
  2. Install the OneSignal Flutter package by adding the following line to your pubspec.yaml file:
dependencies:
  onesignal: ^3.3.0

Initialize OneSignal in your main function:

import 'package:onesignal/onesignal.dart';

void main() {
  OneSignal.shared.init("YOUR_APP_ID");
  OneSignal.shared.setInFocusDisplayType(OSNotificationDisplayType.notification);
  runApp(MyApp());
}

Request permission from the user to show notifications:

await OneSignal.shared.promptUserForPushNotificationPermission();

Send a test notification to make sure everything is set up correctly:

await OneSignal.shared.postNotification(
  OSNotification(
    payload: OSNotificationPayload(
      title: "Test Notification",
      body: "This is a test notification from OneSignal.",
    ),
  ),
);

Listen for notifications in your app and handle them as needed:

OneSignal.shared.setNotificationReceivedHandler((notification) {
  // Handle received notification
});

OneSignal.shared.setNotificationOpenedHandler((notification) {
  // Handle opened notification
});

That’s it! With these steps, you should have a basic integration of OneSignal into your Flutter app. You can customize the notifications and their behavior as needed. Be sure to refer to the OneSignal documentation for more information and additional options.

Share this Article
Leave a comment