Skip to content

Commit

Permalink
Migrate to Flutter 2
Browse files Browse the repository at this point in the history
* Add Null safety support
  • Loading branch information
Jeasmine committed Mar 25, 2021
1 parent 2982cc1 commit ef75a67
Show file tree
Hide file tree
Showing 15 changed files with 235 additions and 218 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ private static HashMap<String, Object> convertEmailSubscriptionStateToMap(OSEmai
static HashMap<String, Object> convertDeviceStateToMap(OSDeviceState state) {
HashMap<String, Object> hash = new HashMap<>();

if (state == null)
return hash;

hash.put("hasNotificationPermission", state.areNotificationsEnabled());
hash.put("pushDisabled", state.isPushDisabled());
hash.put("subscribed", state.isSubscribed());
Expand Down
28 changes: 18 additions & 10 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ class MyApp extends StatefulWidget {

class _MyAppState extends State<MyApp> {
String _debugLabelString = "";
String _emailAddress;
String _externalUserId;
String? _emailAddress;
String? _externalUserId;
bool _enableConsentButton = false;

// CHANGE THIS parameter to true if you want to test GDPR privacy consent
Expand Down Expand Up @@ -140,9 +140,9 @@ class _MyAppState extends State<MyApp> {
void _handleGetDeviceState() async {
print("Getting DeviceState");
OneSignal.shared.getDeviceState().then((deviceState) {
print("DeviceState: ${deviceState.jsonRepresentation()}");
print("DeviceState: ${deviceState?.jsonRepresentation()}");
this.setState(() {
_debugLabelString = deviceState.jsonRepresentation();
_debugLabelString = deviceState?.jsonRepresentation() ?? "Device state null";
});
});
}
Expand All @@ -152,7 +152,7 @@ class _MyAppState extends State<MyApp> {

print("Setting email");

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

void _handleSetExternalUserId() {
print("Setting external user ID");
OneSignal.shared.setExternalUserId(_externalUserId).then((results) {
if (_externalUserId == null) return;

OneSignal.shared.setExternalUserId(_externalUserId!).then((results) {
if (results == null) return;

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

var playerId = deviceState.userId;
if (deviceState == null || deviceState.userId == null)
return;

var playerId = deviceState.userId!;

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

var playerId = deviceState.userId;
if (deviceState == null || deviceState.userId == null)
return;

var playerId = deviceState.userId!;

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

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

// Create a list and bulk remove triggers based on keys supplied
List<String> keys = ["trigger_1", "trigger_3"];
Expand Down
3 changes: 3 additions & 0 deletions example/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,6 @@ flutter:
#
# For details regarding fonts from package dependencies,
# see https://flutter.io/custom-fonts/#from-packages
environment:
sdk: '>=2.12.0 <3.0.0'
flutter: ">=1.10.0 <2.0.0"
54 changes: 29 additions & 25 deletions lib/onesignal_flutter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@ class OneSignal {
MethodChannel _outcomesChannel = const MethodChannel('OneSignal#outcomes');

// event handlers
OpenedNotificationHandler _onOpenedNotification;
SubscriptionChangedHandler _onSubscriptionChangedHandler;
EmailSubscriptionChangeHandler _onEmailSubscriptionChangedHandler;
PermissionChangeHandler _onPermissionChangedHandler;
InAppMessageClickedHandler _onInAppMessageClickedHandler;
NotificationWillShowInForegroundHandler _onNotificationWillShowInForegroundHandler;
OpenedNotificationHandler? _onOpenedNotification;
SubscriptionChangedHandler? _onSubscriptionChangedHandler;
EmailSubscriptionChangeHandler? _onEmailSubscriptionChangedHandler;
PermissionChangeHandler? _onPermissionChangedHandler;
InAppMessageClickedHandler? _onInAppMessageClickedHandler;
NotificationWillShowInForegroundHandler? _onNotificationWillShowInForegroundHandler;

// constructor method
OneSignal() {
Expand Down Expand Up @@ -155,12 +155,13 @@ class OneSignal {
}

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

return result as bool;
return result as bool? ?? false;
}

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

Expand All @@ -190,7 +191,7 @@ class OneSignal {
/// to finish.
Future<Map<String, dynamic>> getTags() async {
Map<dynamic, dynamic> tags =
await _tagsChannel.invokeMethod("OneSignal#getTags");
await (_tagsChannel.invokeMethod("OneSignal#getTags"));
return tags.cast<String, dynamic>();
}

Expand All @@ -207,15 +208,18 @@ class OneSignal {
/// array of keys.
Future<Map<String, dynamic>> deleteTags(List<String> keys) async {
Map<dynamic, dynamic> response =
await _tagsChannel.invokeMethod("OneSignal#deleteTags", keys);
await (_tagsChannel.invokeMethod("OneSignal#deleteTags", keys));
return response.cast<String, dynamic>();
}

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

if ((json.cast<String, dynamic>()).isEmpty)
return null;

return OSDeviceState(json.cast<String, dynamic>());
}

Expand All @@ -232,14 +236,14 @@ class OneSignal {
Future<Map<String, dynamic>> postNotificationWithJson(
Map<String, dynamic> json) async {
Map<dynamic, dynamic> response =
await _channel.invokeMethod("OneSignal#postNotification", json);
await (_channel.invokeMethod("OneSignal#postNotification", json));
return response.cast<String, dynamic>();
}

Future<Map<String, dynamic>> postNotification(
OSCreateNotification notification) async {
Map<dynamic, dynamic> response = await _channel.invokeMethod(
"OneSignal#postNotification", notification.mapRepresentation());
Map<dynamic, dynamic> response = await (_channel.invokeMethod(
"OneSignal#postNotification", notification.mapRepresentation()));
return response.cast<String, dynamic>();
}

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

/// Removes the external user ID that was set for the current user.
Future<Map<String, dynamic>> removeExternalUserId() async {
Map<dynamic, dynamic> results =
await _channel.invokeMethod("OneSignal#removeExternalUserId");
await (_channel.invokeMethod("OneSignal#removeExternalUserId"));
return results.cast<String, dynamic>();
}

Expand Down Expand Up @@ -322,7 +326,7 @@ class OneSignal {
}

/// Get the trigger value associated with the key provided
Future<Object> getTriggerValueForKey(String key) async {
Future<Object?> getTriggerValueForKey(String key) async {
return await _inAppMessagesChannel.invokeMethod("OneSignal#getTriggerValueForKey", key);
}

Expand Down Expand Up @@ -368,27 +372,27 @@ class OneSignal {
Future<Null> _handleMethod(MethodCall call) async {
if (call.method == 'OneSignal#handleOpenedNotification' &&
this._onOpenedNotification != null) {
this._onOpenedNotification(
this._onOpenedNotification!(
OSNotificationOpenedResult(call.arguments.cast<String, dynamic>()));
} else if (call.method == 'OneSignal#subscriptionChanged' &&
this._onSubscriptionChangedHandler != null) {
this._onSubscriptionChangedHandler(
this._onSubscriptionChangedHandler!(
OSSubscriptionStateChanges(call.arguments.cast<String, dynamic>()));
} else if (call.method == 'OneSignal#permissionChanged' &&
this._onPermissionChangedHandler != null) {
this._onPermissionChangedHandler(
this._onPermissionChangedHandler!(
OSPermissionStateChanges(call.arguments.cast<String, dynamic>()));
} else if (call.method == 'OneSignal#emailSubscriptionChanged' &&
this._onEmailSubscriptionChangedHandler != null) {
this._onEmailSubscriptionChangedHandler(
this._onEmailSubscriptionChangedHandler!(
OSEmailSubscriptionStateChanges(call.arguments.cast<String, dynamic>()));
} else if (call.method == 'OneSignal#handleClickedInAppMessage' &&
this._onInAppMessageClickedHandler != null) {
this._onInAppMessageClickedHandler(
this._onInAppMessageClickedHandler!(
OSInAppMessageAction(call.arguments.cast<String, dynamic>()));
} else if (call.method == 'OneSignal#handleNotificationWillShowInForeground' &&
this._onNotificationWillShowInForegroundHandler != null) {
this._onNotificationWillShowInForegroundHandler(
this._onNotificationWillShowInForegroundHandler!(
OSNotificationReceivedEvent(call.arguments.cast<String, dynamic>()));
}
return null;
Expand Down
Loading

0 comments on commit ef75a67

Please sign in to comment.