Skip to content

Commit 6137aca

Browse files
committed
Migrate to Flutter 2
* Add Null safety support
1 parent 2982cc1 commit 6137aca

18 files changed

+285
-273
lines changed

android/src/main/java/com/onesignal/flutter/OneSignalSerializer.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,9 @@ private static HashMap<String, Object> convertEmailSubscriptionStateToMap(OSEmai
5959
static HashMap<String, Object> convertDeviceStateToMap(OSDeviceState state) {
6060
HashMap<String, Object> hash = new HashMap<>();
6161

62+
if (state == null)
63+
return hash;
64+
6265
hash.put("hasNotificationPermission", state.areNotificationsEnabled());
6366
hash.put("pushDisabled", state.isPushDisabled());
6467
hash.put("subscribed", state.isSubscribed());

example/ios/Podfile

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# Uncomment this line to define a global platform for your project
2-
# platform :ios, '9.0'
2+
platform :ios, '10.0'
33

44
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
55
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
@@ -55,7 +55,7 @@ target 'Runner' do
5555
end
5656

5757
target 'OneSignalNotificationServiceExtension' do
58-
pod 'OneSignal', '3.2.0'
58+
pod 'OneSignal', '3.2.2'
5959
end
6060

6161
post_install do |installer|

example/ios/Runner.xcodeproj/project.pbxproj

Lines changed: 47 additions & 52 deletions
Large diffs are not rendered by default.

example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

example/lib/main.dart

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ class MyApp extends StatefulWidget {
1313

1414
class _MyAppState extends State<MyApp> {
1515
String _debugLabelString = "";
16-
String _emailAddress;
17-
String _externalUserId;
16+
String? _emailAddress;
17+
String? _externalUserId;
1818
bool _enableConsentButton = false;
1919

2020
// CHANGE THIS parameter to true if you want to test GDPR privacy consent
@@ -140,9 +140,9 @@ class _MyAppState extends State<MyApp> {
140140
void _handleGetDeviceState() async {
141141
print("Getting DeviceState");
142142
OneSignal.shared.getDeviceState().then((deviceState) {
143-
print("DeviceState: ${deviceState.jsonRepresentation()}");
143+
print("DeviceState: ${deviceState?.jsonRepresentation()}");
144144
this.setState(() {
145-
_debugLabelString = deviceState.jsonRepresentation();
145+
_debugLabelString = deviceState?.jsonRepresentation() ?? "Device state null";
146146
});
147147
});
148148
}
@@ -152,7 +152,7 @@ class _MyAppState extends State<MyApp> {
152152

153153
print("Setting email");
154154

155-
OneSignal.shared.setEmail(email: _emailAddress).whenComplete(() {
155+
OneSignal.shared.setEmail(email: _emailAddress!).whenComplete(() {
156156
print("Successfully set email");
157157
}).catchError((error) {
158158
print("Failed to set email with error: $error");
@@ -201,7 +201,9 @@ class _MyAppState extends State<MyApp> {
201201

202202
void _handleSetExternalUserId() {
203203
print("Setting external user ID");
204-
OneSignal.shared.setExternalUserId(_externalUserId).then((results) {
204+
if (_externalUserId == null) return;
205+
206+
OneSignal.shared.setExternalUserId(_externalUserId!).then((results) {
205207
if (results == null) return;
206208

207209
this.setState(() {
@@ -223,7 +225,10 @@ class _MyAppState extends State<MyApp> {
223225
void _handleSendNotification() async {
224226
var deviceState = await OneSignal.shared.getDeviceState();
225227

226-
var playerId = deviceState.userId;
228+
if (deviceState == null || deviceState.userId == null)
229+
return;
230+
231+
var playerId = deviceState.userId!;
227232

228233
var imgUrlString =
229234
"http://cdn1-www.dogtime.com/assets/uploads/gallery/30-impossibly-cute-puppies/impossibly-cute-puppy-2.jpg";
@@ -249,7 +254,10 @@ class _MyAppState extends State<MyApp> {
249254
void _handleSendSilentNotification() async {
250255
var deviceState = await OneSignal.shared.getDeviceState();
251256

252-
var playerId = deviceState.userId;
257+
if (deviceState == null || deviceState.userId == null)
258+
return;
259+
260+
var playerId = deviceState.userId!;
253261

254262
var notification = OSCreateNotification.silentNotification(
255263
playerIds: [playerId], additionalData: {'test': 'value'});
@@ -280,8 +288,8 @@ class _MyAppState extends State<MyApp> {
280288
OneSignal.shared.removeTriggerForKey("trigger_2");
281289

282290
// Get the value for a trigger by its key
283-
Object triggerValue = await OneSignal.shared.getTriggerValueForKey("trigger_3");
284-
print("'trigger_3' key trigger value: " + triggerValue.toString());
291+
Object? triggerValue = await OneSignal.shared.getTriggerValueForKey("trigger_3");
292+
print("'trigger_3' key trigger value: ${triggerValue?.toString() ?? null}");
285293

286294
// Create a list and bulk remove triggers based on keys supplied
287295
List<String> keys = ["trigger_1", "trigger_3"];

example/pubspec.yaml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,3 +57,6 @@ flutter:
5757
#
5858
# For details regarding fonts from package dependencies,
5959
# see https://flutter.io/custom-fonts/#from-packages
60+
environment:
61+
sdk: '>=2.12.0 <3.0.0'
62+
flutter: ">=1.10.0 <2.0.0"

lib/onesignal_flutter.dart

Lines changed: 29 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -40,12 +40,12 @@ class OneSignal {
4040
MethodChannel _outcomesChannel = const MethodChannel('OneSignal#outcomes');
4141

4242
// event handlers
43-
OpenedNotificationHandler _onOpenedNotification;
44-
SubscriptionChangedHandler _onSubscriptionChangedHandler;
45-
EmailSubscriptionChangeHandler _onEmailSubscriptionChangedHandler;
46-
PermissionChangeHandler _onPermissionChangedHandler;
47-
InAppMessageClickedHandler _onInAppMessageClickedHandler;
48-
NotificationWillShowInForegroundHandler _onNotificationWillShowInForegroundHandler;
43+
OpenedNotificationHandler? _onOpenedNotification;
44+
SubscriptionChangedHandler? _onSubscriptionChangedHandler;
45+
EmailSubscriptionChangeHandler? _onEmailSubscriptionChangedHandler;
46+
PermissionChangeHandler? _onPermissionChangedHandler;
47+
InAppMessageClickedHandler? _onInAppMessageClickedHandler;
48+
NotificationWillShowInForegroundHandler? _onNotificationWillShowInForegroundHandler;
4949

5050
// constructor method
5151
OneSignal() {
@@ -155,12 +155,13 @@ class OneSignal {
155155
}
156156

157157
/// in iOS, will prompt the user for permission to send push notifications.
158+
// in Android, it will always return false, since notification permission is by default given
158159
Future<bool> promptUserForPushNotificationPermission(
159160
{bool fallbackToSettings = false}) async {
160161
dynamic result = await _channel.invokeMethod(
161162
"OneSignal#promptPermission", {'fallback': fallbackToSettings});
162163

163-
return result as bool;
164+
return result as bool? ?? false;
164165
}
165166

166167
/// Sends a single key/value pair to tags to OneSignal.
@@ -179,7 +180,7 @@ class OneSignal {
179180
/// waiting for this request to complete.
180181
Future<Map<String, dynamic>> sendTags(Map<String, dynamic> tags) async {
181182
Map<dynamic, dynamic> response =
182-
await _tagsChannel.invokeMethod("OneSignal#sendTags", tags);
183+
await (_tagsChannel.invokeMethod("OneSignal#sendTags", tags));
183184
return response.cast<String, dynamic>();
184185
}
185186

@@ -190,7 +191,7 @@ class OneSignal {
190191
/// to finish.
191192
Future<Map<String, dynamic>> getTags() async {
192193
Map<dynamic, dynamic> tags =
193-
await _tagsChannel.invokeMethod("OneSignal#getTags");
194+
await (_tagsChannel.invokeMethod("OneSignal#getTags"));
194195
return tags.cast<String, dynamic>();
195196
}
196197

@@ -207,15 +208,18 @@ class OneSignal {
207208
/// array of keys.
208209
Future<Map<String, dynamic>> deleteTags(List<String> keys) async {
209210
Map<dynamic, dynamic> response =
210-
await _tagsChannel.invokeMethod("OneSignal#deleteTags", keys);
211+
await (_tagsChannel.invokeMethod("OneSignal#deleteTags", keys));
211212
return response.cast<String, dynamic>();
212213
}
213214

214215
/// Returns an `OSDeviceState` object, which contains the current device state
215-
Future<OSDeviceState> getDeviceState() async {
216+
Future<OSDeviceState?> getDeviceState() async {
216217
var json =
217218
await _channel.invokeMethod("OneSignal#getDeviceState");
218219

220+
if ((json.cast<String, dynamic>()).isEmpty)
221+
return null;
222+
219223
return OSDeviceState(json.cast<String, dynamic>());
220224
}
221225

@@ -232,14 +236,14 @@ class OneSignal {
232236
Future<Map<String, dynamic>> postNotificationWithJson(
233237
Map<String, dynamic> json) async {
234238
Map<dynamic, dynamic> response =
235-
await _channel.invokeMethod("OneSignal#postNotification", json);
239+
await (_channel.invokeMethod("OneSignal#postNotification", json));
236240
return response.cast<String, dynamic>();
237241
}
238242

239243
Future<Map<String, dynamic>> postNotification(
240244
OSCreateNotification notification) async {
241-
Map<dynamic, dynamic> response = await _channel.invokeMethod(
242-
"OneSignal#postNotification", notification.mapRepresentation());
245+
Map<dynamic, dynamic> response = await (_channel.invokeMethod(
246+
"OneSignal#postNotification", notification.mapRepresentation()));
243247
return response.cast<String, dynamic>();
244248
}
245249

@@ -270,7 +274,7 @@ class OneSignal {
270274
/// Identity Verification. The email auth hash is a hash of your app's API key and the
271275
/// user ID. We recommend you generate this token from your backend server, do NOT
272276
/// store your API key in your app as this is highly insecure.
273-
Future<void> setEmail({String email, String emailAuthHashToken}) async {
277+
Future<void> setEmail({required String email, String? emailAuthHashToken}) async {
274278
return await _channel.invokeMethod("OneSignal#setEmail",
275279
{'email': email, 'emailAuthHashToken': emailAuthHashToken});
276280
}
@@ -284,16 +288,16 @@ class OneSignal {
284288
/// OneSignal allows you to set a custom ID for your users. This makes it so that
285289
/// if your app has its own user ID's, you can use your own custom user ID's with
286290
/// our API instead of having to save their OneSignal user ID's.
287-
Future<Map<String, dynamic>> setExternalUserId(String externalId, [String authHashToken]) async {
291+
Future<Map<String, dynamic>> setExternalUserId(String externalId, [String? authHashToken]) async {
288292
Map<dynamic, dynamic> results =
289-
await _channel.invokeMethod("OneSignal#setExternalUserId", {'externalUserId' : externalId, 'authHashToken' : authHashToken});
293+
await (_channel.invokeMethod("OneSignal#setExternalUserId", {'externalUserId' : externalId, 'authHashToken' : authHashToken}));
290294
return results.cast<String, dynamic>();
291295
}
292296

293297
/// Removes the external user ID that was set for the current user.
294298
Future<Map<String, dynamic>> removeExternalUserId() async {
295299
Map<dynamic, dynamic> results =
296-
await _channel.invokeMethod("OneSignal#removeExternalUserId");
300+
await (_channel.invokeMethod("OneSignal#removeExternalUserId"));
297301
return results.cast<String, dynamic>();
298302
}
299303

@@ -322,7 +326,7 @@ class OneSignal {
322326
}
323327

324328
/// Get the trigger value associated with the key provided
325-
Future<Object> getTriggerValueForKey(String key) async {
329+
Future<Object?> getTriggerValueForKey(String key) async {
326330
return await _inAppMessagesChannel.invokeMethod("OneSignal#getTriggerValueForKey", key);
327331
}
328332

@@ -368,27 +372,27 @@ class OneSignal {
368372
Future<Null> _handleMethod(MethodCall call) async {
369373
if (call.method == 'OneSignal#handleOpenedNotification' &&
370374
this._onOpenedNotification != null) {
371-
this._onOpenedNotification(
375+
this._onOpenedNotification!(
372376
OSNotificationOpenedResult(call.arguments.cast<String, dynamic>()));
373377
} else if (call.method == 'OneSignal#subscriptionChanged' &&
374378
this._onSubscriptionChangedHandler != null) {
375-
this._onSubscriptionChangedHandler(
379+
this._onSubscriptionChangedHandler!(
376380
OSSubscriptionStateChanges(call.arguments.cast<String, dynamic>()));
377381
} else if (call.method == 'OneSignal#permissionChanged' &&
378382
this._onPermissionChangedHandler != null) {
379-
this._onPermissionChangedHandler(
383+
this._onPermissionChangedHandler!(
380384
OSPermissionStateChanges(call.arguments.cast<String, dynamic>()));
381385
} else if (call.method == 'OneSignal#emailSubscriptionChanged' &&
382386
this._onEmailSubscriptionChangedHandler != null) {
383-
this._onEmailSubscriptionChangedHandler(
387+
this._onEmailSubscriptionChangedHandler!(
384388
OSEmailSubscriptionStateChanges(call.arguments.cast<String, dynamic>()));
385389
} else if (call.method == 'OneSignal#handleClickedInAppMessage' &&
386390
this._onInAppMessageClickedHandler != null) {
387-
this._onInAppMessageClickedHandler(
391+
this._onInAppMessageClickedHandler!(
388392
OSInAppMessageAction(call.arguments.cast<String, dynamic>()));
389393
} else if (call.method == 'OneSignal#handleNotificationWillShowInForeground' &&
390394
this._onNotificationWillShowInForegroundHandler != null) {
391-
this._onNotificationWillShowInForegroundHandler(
395+
this._onNotificationWillShowInForegroundHandler!(
392396
OSNotificationReceivedEvent(call.arguments.cast<String, dynamic>()));
393397
}
394398
return null;

0 commit comments

Comments
 (0)