Skip to content

Instantly share code, notes, and snippets.

@knaeckeKami
Created February 6, 2025 21:02
Show Gist options
  • Save knaeckeKami/ae701105bc5cd1dd1bd1ae79872f6866 to your computer and use it in GitHub Desktop.
Save knaeckeKami/ae701105bc5cd1dd1bd1ae79872f6866 to your computer and use it in GitHub Desktop.
class NotificationHandler {
static const MethodChannel _channel = MethodChannel('com.helloinside.glucose/notification');
final void Function(Object, bool isAppLaunch) onNotificationTap;
NotificationHandler({required this.onNotificationTap});
void initialize() {
_channel.setMethodCallHandler(handleMethodCall);
/// let the native side know that the channel is initialized, and it can start sending notifications
_channel.invokeMethod("initializeChannel");
/// check if there is a notification that was tapped while the app was in the background
/// and handle it
/// the tap would have been lost otherwise, since this handler is initialized after the tap
_channel.invokeMethod("getLastNotificationData").then((Object? value) {
if (value != null) {
onNotificationTap(value, true);
}
});
}
Future<void> handleMethodCall(MethodCall call) {
try {
switch (call.method) {
case 'onNotificationTap':
_handleNotificationTap(call);
break;
default:
log.warning('Unknown method: ${call.method}');
}
} catch (e, s) {
log.error('Error in NotificationHandler: $e', e, s);
}
return Future.value();
}
void dispose() {
_channel.setMethodCallHandler(null);
}
void _handleNotificationTap(MethodCall call) {
log.debug('NotificationHandler: _handleNotificationTap: $call');
final args = call.arguments as Map<Object?, Object?>;
final payload = args['payload'];
log.warning("_handleNotificationTap: args $args / $payload");
onNotificationTap(payload ?? args, false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment