One Signal Notifications in Flutter
In this tutorial, I will explain how you can implement One Signal Notifications in your flutter app ‘ Android and IOS ’ so let’s do it >>
first of all, add this dependency to your pubspec.yaml file :
onesignal_flutter: ^2.0.0
Run flutter packages get to install the SDK.
Setup for Android :
In the very top (Line:1 ) of android/app/build.gradle “App-level” add the following code:
buildscript {
repositories {
// ...
maven { url 'https://plugins.gradle.org/m2/' } // Gradle Plugin Portal
}
dependencies {
// ...
// OneSignal-Gradle-Plugin
classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.6, 0.99.99]'
}
}
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
Setup for IOS :
Open your Xcode project.
Select File > New > Target
Select Notification Service Extension and press Next
Enter the product name as “OneSignalNotificationServiceExtension” and hit Next
Close the Xcode project.
delete pod file/pods folder and podfile.lock
then from the terminal :
cd ios
pod deintegrate
flutter run
In the /ios directory of your project, open the Podfile and add the following code to the bottom :
target ‘OneSignalNotificationServiceExtension’ do
use_frameworks!
pod ‘OneSignal’, ‘>= 2.9.3’, ‘< 3.0’
end
Open terminal, cd to the /ios directory, and run pod install.
then In your XCode project, in the NotificationService.swift replace all code with :
import UserNotifications
import OneSignal
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var receivedRequest: UNNotificationRequest!
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.receivedRequest = request;
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
if let bestAttemptContent = bestAttemptContent {
OneSignal.didReceiveNotificationExtensionRequest(self.receivedRequest, with: self.bestAttemptContent)
contentHandler(bestAttemptContent)
}
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your “best attempt” at modified content, otherwise the original push payload will be used.
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
OneSignal.serviceExtensionTimeWillExpireRequest(self.receivedRequest, with: self.bestAttemptContent)
contentHandler(bestAttemptContent)
}
}
}
- Select your project settings and under Capabilities, enable Push Notifications
- Next, enable Background Modes and check Push Notifications
GREAT !!
Now let’s go to one signal website: https://onesignal.com/
sign up or sign in if you already have an account :
create an app to get API Key and follow the steps there
now in your main file make the main function like this void main()async{}
and inside the main function add this code before running the app :
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
OneSignal.shared.init('fb4fba96-6d4b-453b-863a-c3d97swe-43450', iOSSettings: {
OSiOSSettings.autoPrompt: false,
OSiOSSettings.inAppLaunchUrl: false
});
OneSignal.shared
.setInFocusDisplayType(OSNotificationDisplayType.notification);
await OneSignal.shared
.promptUserForPushNotificationPermission(fallbackToSettings: true);
and in your home page add this code
String subtitle = '';
String content = '';
String data = '';
@override
void initState() {
super.initState();
OneSignal.shared
.setNotificationReceivedHandler((OSNotification notification) {
setState(() {
subtitle = notification.payload.subtitle;
content = notification.payload.body;
data = notification.payload.additionalData['data'];
});
});
OneSignal.shared
.setNotificationOpenedHandler((OSNotificationOpenedResult result) {
print('Notification Opened');
});
OneSignal.shared.getPermissionSubscriptionState().then((state) {
DocumentReference ref = FirebaseFirestore.instance
.collection('users')
.doc(FirebaseAuth.instance.currentUser.uid);
ref.update({
'osUserID': '${state.subscriptionStatus.userId}',
});
});
}
now to send a notification to specific users use this function:
_sendNotification() {
OneSignal.shared.postNotification(OSCreateNotification(
additionalData: {
'data': 'this is our data',
},
subtitle: 'Flutter in depth',
playerIds: ['eaf2dcd7-a1e2-4cb6-ae5c-c39a3bc3a752a'],
content: 'New series lessons from Code With Ammar',
));
}
and that’s it.
and that’s it Congratulations you can sen notifications
make sure to watch all video on my youtube channel to understand the full code step by step
https://www.youtube.com/c/CodeWithAmmar
I’ll be happy to follow me on my all accounts :
Twitter: https://twitter.com/codewithammar/ Facebook: https://m.facebook.com/codewithammar/ Instagram: https://instagram.com/codewithammar/ Telegram: https://t.me/codewithammar/
Mobile Apps development instructor :
Ammar Awni