Onesignal Flutter

Description: I am facing the following issue with version 2.2.0. Could you please help me on this issue. OneSignal.appContext null, could not read OneSignal from getSharedPreferences. W/OneSignal( 966): java.lang.Throwable W/. @kuccilim The case looks like it worked, I switched to OneSignal 3.0.0-beta and the notifications also worked. But after doing flutter clean and starting the payload project, it did not start setNotificationOpenedHandler.
Push Notification trong lập trình ứng dụng là một phần không thể thiếu và trong lập trình Ứng dụng Flutter cũng như vậy.
Trong bài viết này Báo Flutter sẽ chia sẻ về push Notification sử dụng One Signal, dưới sự hướng dẫn của thành viên thuộc đội ngũ Báo Flutter.
Cài đặt
Tạo Push Notification sử dụng OneSignal thì trước hết chúng ta cần tài khoản trên OneSignal, vào OneSignal.com và tạo project mới.
1. Android
– Ở mục Setting>Platfom chọn Google Android
– Ở đây chúng ta cần tạo project Firebase để nhập Firebase Server Key và Firebase Sender ID.
– Sau khi tạo Firebase project mới xong Chọn vào Icon Setting > Project Setting
– Chọn Cloud Messaging và chúng ta sẽ lấy được Firebase Server Key và Firebase Sender ID.
– Add vào trường trên và Next > Chọn Native Android > Next > Save
2. IOS001d
Cài đặt Push Notification Flutter trong iOS tương tự theo link này.
Thêm thư viện
Quay lại Flutter project của chúng ta, tại file pubspec.yaml thêm thư viện : onesignal_flutter
Ví dụ :
Sau đó chạy Pub get hay run trên terminal: flutter packages get
Start Coding
Tại thư mục android/app/build.grade thêm vào trên cùng dòng đầu tiên (dòng 1):
2 4 6 8 10 12 | 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' |
Khởi tạo OneSignal :
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 | if(!mounted)return; OneSignal.shared.setLogLevel(OSLogLevel.verbose,OSLogLevel.none); OneSignal.shared.setRequiresUserPrivacyConsent(_requireConsent); varsettings={ OSiOSSettings.promptBeforeOpeningPushUrl:true OneSignal.shared.setNotificationReceivedHandler((OSNotification notification){ _debugLabelString= 'Received notification: n${notification.jsonRepresentation().replaceAll('n', 'n')}'; }); OneSignal.shared .setNotificationOpenedHandler((OSNotificationOpenedResult result){ _debugLabelString= 'Opened notification: n${result.notification.jsonRepresentation().replaceAll('n', 'n')}'; }); OneSignal.shared .setInAppMessageClickedHandler((OSInAppMessageAction action){ _debugLabelString= 'In App Message Clicked: n${action.jsonRepresentation().replaceAll('n', 'n')}'; }); OneSignal.shared .setSubscriptionObserver((OSSubscriptionStateChanges changes){ print('SUBSCRIPTION STATE CHANGED: ${changes.jsonRepresentation()}'); OneSignal.shared.setPermissionObserver((OSPermissionStateChanges changes){ print('PERMISSION STATE CHANGED: ${changes.jsonRepresentation()}'); (OSEmailSubscriptionStateChanges changes){ print('EMAIL SUBSCRIPTION STATE CHANGED ${changes.jsonRepresentation()}'); // NOTE: Replace with your own app ID from https://www.onesignal.com .init('your-app_id-is-here',iOSSettings:settings); OneSignal.shared .setInFocusDisplayType(OSNotificationDisplayType.notification); boolrequiresConsent=await OneSignal.shared.requiresUserPrivacyConsent(); this.setState((){ }); |

Chú ý
Thêm API key của bạn ở dòng bên dưới :
2 | .init('your-app_id-here',iOSSettings:settings); |
Ảnh bên dưới là hướng dẫn lấy app_id và API key
– Chúng ta đã tiến hành khởi tạo OneSignal rồi. Nhưng như thế vẫn chưa đủ, Chúng ta cần thêm dòng sau:

Nếu ứng dụng của bạn được thiết lập để yêu cầu sự đồng ý của User trước khi sử dụng push notifications. Thì phương thức này cần được gọi khi người dùng đưa ra sự đồng ý của họ.
Ví dụ: Bạn có 1 Dialog có các action [“Có”, “Không” ] xuất hiện với content : “Bạn có muốn nhận thông báo từ dịch vụ của chúng tôi không?” khi User chọn “Có” thì cũng chính là lúc phương thức này cần được gọi.
Còn nếu không muốn yêu cầu sự đồng ý của user thì hãy gọi nó trong hàm khởi tạo.
Phương thức này sẽ khiến cho OneSignal SDK khởi chạy.
– Nếu bạn muốn push notification Từ device của bạn, bạn có thể theo dòng code sau:
Onesignal Notification
2 4 6 8 10 12 14 16 18 20 | varstatus=await OneSignal.shared.getPermissionSubscriptionState(); varimgUrlString= 'http://cdn1-www.dogtime.com/assets/uploads/gallery/30-impossibly-cute-puppies/impossibly-cute-puppy-2.jpg'; varnotification=OSCreateNotification( content:'this is a test from OneSignal's Flutter SDK', iosAttachments:{'id1':imgUrlString}, buttons:[ OSActionButton(text:'test2',id:'id2') varresponse=await OneSignal.shared.postNotification(notification); } |
Notification Platform
3. REST API
Như vậy là chúng ta đã khởi tạo xong OneSignal trên Flutter.
Vậy câu hỏi đặt ra là “Vậy làm thế nào để tôi gửi thông báo từ backend của tôi ?”
Câu trả lời là: “……Ờ thì.. Cũng dễ thôi :D”
OneSignal hỗ trợ cho việc tạo notification qua việc REST API
Ở trường hợp này , tôi sử dụng Postman để thử nghiệm
– Trước hết đây là phương thức Post với base url: https://onesignal.com/api/v1/notifications
Chúng ta tiến hành add Api key đã lấy ở trên của chúng ta như trên hình.
Sau đó ta qua mục Body > chọn raw và add đoạn json sau vào:
Onesignal Push
2 4 6 | 'app_id':'your app_id', 'contents':{'en':'This is the message body!'}, } |
Nhớ thay app_id của bạn vào. Sau đó SEND….. và ting ting… Thông báo của bạn đã được gửi.
One Signal App

Bạn có thể đọc thêm về REST API OneSignal tại : https://documentation.onesignal.com/reference/create-notification
Sourcecode của bài hướng dẫn này trên Github tại đây
Như vậy, Bài viết đã hướng dẫn cho bạn cách để sử dụng OneSignal cho việc push notification trong lập trình ứng dụng Flutter. Hy vọng bài viết giúp ích cho bạn.
Chúc các bạn có được nhiều kiến thức từ Báo Flutter
Tác giả bài viết
Nguyễn Mạnh Hùng
Flutter Software Engineer tại Báo Flutter