Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

OneSignal profile imageonesignaldevs
onesignaldevs forOneSignal

Posted on • Originally published atonesignal.com on

     

How to Add Push Notifications to a Flutter App

How to Add Push Notifications to a Flutter App

Push notifications have proved to be one of the most effective ways to enhance your user experience, improve app engagement, and boost retention. In this tutorial, we’ll show you how to integratepush notifications in your iOS and Android apps with minor configuration changes using theOneSignal Flutter SDK. In no time, you'll be able to send out transactional and promotional push notifications to users for free!

If you are a Flutter developer and want to leverage push notifications to engage with your users, follow along to add this amazing functionality to your apps.

Guide Overview:

Part 1: Set Up Your OneSignal Account

To begin,log in to your OneSignal account orcreate a free account. Then, click on the blue button entitled _New App/Website _ to configure your OneSignal account to fit your app or website.

How to Add Push Notifications to a Flutter App

Add your app name, select _Google Android _ if the target is Android devices or select _Apple iOS _ if the target is iOS devices. Then click,Next: Configure Your Platform.

How to Add Push Notifications to a Flutter App

For iOS, you will need toadd an iOS push certificate. If you're not sure about this step, read OneSignal'sinstructions on how to generate an iOS push certificate.

How to Add Push Notifications to a Flutter App
Apple iOS (APNs) Configuration in OneSignal

For Android, you will need to enterFirebase Server Key andServer ID that you can get by creating a new project on Firebase Console.

How to Add Push Notifications to a Flutter App
Google Android (FCM) Configuration in OneSignal

To find the Firebase service key, log in to the Firebase console and click onAdd Project.

How to Add Push Notifications to a Flutter App

Add the name of your project and turn offEnable Google Analytics for this project if you want, then click onCreate Project.

How to Add Push Notifications to a Flutter App

How to Add Push Notifications to a Flutter App

Click _Create project _ to save the new entry, then click _continue _.

How to Add Push Notifications to a Flutter App

You’ll be directed to the project dashboard where you have to click on the Setting icon next to _Project Overview _ and click on _Project Settings _ from the menu that appears.

How to Add Push Notifications to a Flutter App
Navigate to the project settings menu in the Firebase console.

In theCloud Messaging tab, you’ll be able to find theFirebase Server Key andServer ID. Navigate back to your OneSignal dashboard and copy and paste those values into the appropriate fields underOneSignal Google Android(FCM) Configuration like this:

How to Add Push Notifications to a Flutter App
Input your Firebase Server Key and Sender ID in OneSignal.

After clicking onSave & Continue , you’ll be asked to select your target SDK. ChooseFlutter.

How to Add Push Notifications to a Flutter App
Choose Flutter as your target SDK.

ClickSave & Continue again and then clickDone at the bottom of the screen.

How to Add Push Notifications to a Flutter App
View your app ID in OneSignal to finish the Google Android FCM configuration process.

Now, you should see your app dashboard on OneSignal under the _Settings>Platforms _ tab. On this page under _Native App _ _platforms, you should see an **_Active** tag next to _Google Android, _ which means you’re ready to send notifications to users using the Android version of your Flutter app. If you followed the iOS setup, you should see an _Active _ tag next to _Apple iOS _.

How to Add Push Notifications to a Flutter App
An "Active" tag is displayed next to Google Android in the OneSignal dashboard.

Part 2: Creating a Flutter App

So the first thing you need to do after creating a new Flutter project is to add theonesignal_flutter dependency. To do that, visitpub.dev and search foronesignal_flutter.

How to Add Push Notifications to a Flutter App
Shows onesignal_flutter 3.2.7 in pub.dev.

Add the latest version ofonesignal_flutter topubspec.yaml under the dependencies section with the version number from pub.dev.

How to Add Push Notifications to a Flutter App

Now openmain.dart and removeMyHomePage() class (or just its contents).

How to Add Push Notifications to a Flutter App
Remove the content of MyHomePage() from main.dart.

Create a new dart file namedhome.dart (or continue in themain.dart file) and create a stateful widget by the nameHome like this:

class Home extends StatefulWidget {const Home({Key? key}) : super(key: key);@override_HomeState createState() => _HomeState();}class _HomeState extends State<Home> {@overrideWidget build(BuildContext context) {return Container();}}
Enter fullscreen modeExit fullscreen mode

Next, build a simple UI by adding a few widgets likeContainer,Column andText in theHome class.

@overrideWidget build(BuildContext context) {return Scaffold(body: Container(child: Column(mainAxisAlignment: MainAxisAlignment.center,crossAxisAlignment: CrossAxisAlignment.center,children: const [Text("Hello"),],),),);}
Enter fullscreen modeExit fullscreen mode

Now you can add theOneSignal App ID which you can find in your OneSignal dashboard under theKeys & IDs tab.

How to Add Push Notifications to a Flutter App

Copy theOneSignal App ID and add it into your Flutter app inmain.dart as a constant.

static final String oneSignalAppId = "16090413-4b70-4c0b-a9f4-dd43c445ccee";
Enter fullscreen modeExit fullscreen mode

Then add SDK initialization code to yourXXX.

Future<void> initPlatformState() async {   OneSignal.shared.setAppId(oneSignalAppId);   OneSignal.shared       .promptUserForPushNotificationPermission()       .then((accepted) {}); }
Enter fullscreen modeExit fullscreen mode

Also, initialize state.

@override void initState() {   super.initState();   initPlatformState(); }
Enter fullscreen modeExit fullscreen mode

Complete Code(main.dart)

import 'package:flutter/material.dart';import 'package:onesignal_flutter/onesignal_flutter.dart';class Home extends StatefulWidget { const Home({Key? key}) : super(key: key); @override _HomeState createState() => _HomeState();}class _HomeState extends State<Home> { @override void initState() {   super.initState();   initPlatformState(); } static final String oneSignalAppId = "16090413-4b70-4c0b-a9f4-dd43c445ccee"; Future<void> initPlatformState() async {   OneSignal.shared.setAppId(oneSignalAppId);   OneSignal.shared       .promptUserForPushNotificationPermission()       .then((accepted) {}); } @override Widget build(BuildContext context) {   return Scaffold(     body: Container(       child: Column(         mainAxisAlignment: MainAxisAlignment.center,         crossAxisAlignment: CrossAxisAlignment.center,         children: const [           Text("Hello"),         ],       ),     ),   ); }}
Enter fullscreen modeExit fullscreen mode

Run your Flutter app on your physical device or emulator.

In case you recievecompileSdkVersion error then go to yourapp-level build.gradle file and updatecompileSDKVersion to31.

defaultConfig {// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).applicationId "com.example.flutter_onesignal"minSdkVersion 16compileSdkVersion 31targetSdkVersion 30versionCode flutterVersionCode.toInteger()versionName flutterVersionName}
Enter fullscreen modeExit fullscreen mode

If you getKotlin Version error then go to yourbuild.gradle file in the root of your Android directory and upgrade yourKotlin_version to the latest version (ext.kotlin_version = '1.5.10')

For the iOS version, there’s are some additional steps that need to be completed. The first one is to add an iOS service extension.

The OneSignalNotificationServiceExtension allows your application (in iOS) to receive rich notifications with images and buttons, along with badges andConfirmed Deliveries.

The first step is to navigate to your Flutter project's iOS folder and open the.xcworkspace file in Xcode. You can use theopen ios/Runner.xcworkspace command in the terminal to do the same.

Then selectFile >New >Target.

How to Add Push Notifications to a Flutter App

SelectNotification Service Extension and pressNext.

How to Add Push Notifications to a Flutter App

Add the product name asOneSignalNotificationExtension and change the language to _Object-C _ orSwift according to your needs. The team account should be your account or your organization’s account.

How to Add Push Notifications to a Flutter App
Add the product name as OneSignalNotificationExtension in Flutter.

Click the _Finish _ at the bottom right corner of the window, but when prompted to “Activate” scheme click on _Cancel _.

How to Add Push Notifications to a Flutter App
Click "Cancel" when prompted to activate the scheme.

By canceling, you are keeping Xcode set to debug your app rather than using the extension. If you select _Activate _ by accident, you can simply switch back to debug your app in Xcode (next to the Play button).

Now, open the Xcode project settings and select the _OneSignalNotificationServiceExtension _ target. Under the _Deployment info _ section on this page, select iOS 10.0 as the target unless there are any reason for using higher versions.

How to Add Push Notifications to a Flutter App

Now, close the Xcode project and go back to your Flutter development IDE. In the/ios directory of your project, open thePodfile and add the following lines outside of the main target (they should be at the same level as your main target):

target 'OneSignalNotificationServiceExtension' douse_frameworks!pod 'OneSignalXCFramework', '>= 3.4.3', '< 4.0'end
Enter fullscreen modeExit fullscreen mode

How to Add Push Notifications to a Flutter App

Also, make sure to uncomment the platform line at the top of thePodfile. It can be iOS version 9.0 or higher according to your needs.

How to Add Push Notifications to a Flutter App

Now Open the terminal, cd to the ios directory, and run pod install.

How to Add Push Notifications to a Flutter App

If you see the error below, remove# from the above in front ofuse_frameworks! and try again.

- Runner (true) and OneSignalNotificationServiceExtension (false) do not both set use_frameworks!.

Open the<project-name>.xcworkspace file. In your project, in theOneSignalNotificationServiceExtension/ folder, openNotificationService.m.

How to Add Push Notifications to a Flutter App

Replace the whole file contents with the following code for Objective-C:

#import <OneSignal/OneSignal.h>#import "NotificationService.h"@interface NotificationService ()@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);@property (nonatomic, strong) UNNotificationRequest *receivedRequest;@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;@end@implementation NotificationService- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {   self.receivedRequest = request;   self.contentHandler = contentHandler;   self.bestAttemptContent = [request.content mutableCopy];   //If your SDK version is < 3.5.0 uncomment and use this code:   /*   [OneSignal didReceiveNotificationExtensionRequest:self.receivedRequest                      withMutableNotificationContent:self.bestAttemptContent];   self.contentHandler(self.bestAttemptContent);   */   /* DEBUGGING: Uncomment the 2 lines below and comment out the one above to ensure this extension is excuting                 Note, this extension only runs when mutable-content is set                 Setting an attachment or action buttons automatically adds this */   // NSLog(@"Running NotificationServiceExtension");   // self.bestAttemptContent.body = [@"[Modified] " stringByAppendingString:self.bestAttemptContent.body];   // Uncomment this line to set the default log level of NSE to VERBOSE so we get all logs from NSE logic   //[OneSignal setLogLevel:ONE_S_LL_VERBOSE visualLevel:ONE_S_LL_NONE];   [OneSignal didReceiveNotificationExtensionRequest:self.receivedRequest                      withMutableNotificationContent:self.bestAttemptContent                                  withContentHandler:self.contentHandler];}- (void)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.   [OneSignal serviceExtensionTimeWillExpireRequest:self.receivedRequest withMutableNotificationContent:self.bestAttemptContent];   self.contentHandler(self.bestAttemptContent);}@end
Enter fullscreen modeExit fullscreen mode

For Swift, replace it with:

import UserNotificationsimport OneSignalclass 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       self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)       if let bestAttemptContent = bestAttemptContent {           //If your SDK version is < 3.5.0 uncomment and use this code:           /*           OneSignal.didReceiveNotificationExtensionRequest(self.receivedRequest, with: self.bestAttemptContent)           contentHandler(bestAttemptContent)           */           /* DEBUGGING: Uncomment the 2 lines below to check this extension is excuting                         Note, this extension only runs when mutable-content is set                         Setting an attachment or action buttons automatically adds this */           //OneSignal.setLogLevel(.LL_VERBOSE, visualLevel: .LL_NONE)           //bestAttemptContent.body = "[Modified] " + bestAttemptContent.body           OneSignal.didReceiveNotificationExtensionRequest(self.receivedRequest, with: bestAttemptContent, withContentHandler: self.contentHandler)       }   }   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)       }   }}
Enter fullscreen modeExit fullscreen mode

You also need to enable anApp Group to useConfirmed Deliveries and increment/decrementBadges through push notifications. For that, you can follow theiOS SDK App Groups setup guide to add the OneSignal App Group in your app.

Now you need to enablepush capability for iOS apps. Open your.xcworkspace file in Xcode.

In the main app target, selectSigning & Capabilities >All >+ Capability and then search "push." Double-click on _Push Notifications _ to enable it.

How to Add Push Notifications to a Flutter App

Next, enableBackground Modes and checkRemote Notifications.

How to Add Push Notifications to a Flutter App

Now you are ready to send notifications from the OneSignal dashboard!

Back in your OneSignal dashboard, click onMessages in the top navigation menu and select _Push _ from the sub-menu. Click the+New Push button to create your first notification.

Note: Notifications are enabled on Android devices by default if you have disabled your notifications, make sure youenable them again. If you're sending a notification to an iOS device, you will need to opt-in to notifications in your app settings.

How to Add Push Notifications to a Flutter App
Click the "+New Push" button in your OneSignal dashboard.

You will be redirected to a new window that will allow you to customize your push notification. Under _Audience _, make sure that _Send to Subscribed Users _ is selected. Then, create your message by adding your message title, content, and image. Because this is the first notification your subscribers will receive, you may choose to craft a simple welcome message to confirm that they've been subscribed and reinforce the value that notifications will provide.

Under the _Delivery Schedule _ section, select _Immediately _ and _Send to everyone at the same time _ to send to all your current pushsubscribers. If you have just finished setting up your OneSignal account, chances are you're the first and onlysubscriber. If your app or website is heavily trafficked and other users have already opted in to receive push notifications, you may want to selectSend to a particular segment(s) to test your message out on a specific audience.

How to Add Push Notifications to a Flutter App
Specify the audience for your push notification in OneSignal.

Add your message title and copy and preview how your message looks on your target device.

How to Add Push Notifications to a Flutter App

When you're ready to send your message, click on the blue _Review and Send _ button at the bottom of the screen.

How to Add Push Notifications to a Flutter App

A small popup will appear for you to review your message. Once you are satisfied, click on the blue _Send Message _ button. You should receive a push notification on your device! 🚀

How to Add Push Notifications to a Flutter App

You’re done🎊!

You’ll receive the notification on your physical device that you used to run your Flutter app or on the emulator.

How to Add Push Notifications to a Flutter App

After the message sends, you'll be directed to theDelivery page where you can view the send report and track engagement.

Still have questions?

Check out our completeOneSignal Flutter SDK Documentation.

This post was guest authored byAkanksha Singh.

Top comments(3)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
nabeena profile image
Nabeena
  • Joined

Is it possible to send notification from another server api(like using php) to flutter android application using this SDK?

CollapseExpand
 
onesignaldevs profile image
onesignaldevs
The latest news, technical content, video, and events from OneSignal's Developers. Helping 1M+ devs deliver 8B+ messages daily.
  • Work
    OneSignal at OneSignal
  • Joined

You can use the REST API to send the notifications to any device regardless you used Flutter, React, or whatever
onesignal.com/blog/how-to-send-pus...

CollapseExpand
 
nabeena profile image
Nabeena
  • Joined

Okay. That's great. Thank you for your reply

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

More fromOneSignal

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp