showPipAdView method
Displays the interstitial ad and starts listening for ad events.
This method triggers the native interstitial ad view with the given parameters
and sets up a listener to handle adClicked and adAppeared events.
Parameters:
adData(Map<String, dynamic>): Required ad metadata to display the ad.width(int?): Optional width of the interstitial ad view in pixels.height(int?): Optional height of the interstitial ad view in pixels.onAdClicked(void Function(Map? ad)?): Optional callback triggered when the ad is clicked.onAdAppeared(void Function(Map? ad, String? cliUbid?): Optional callback triggered when the ad appears.
Returns: Future<void> .
Implementation
Future<void>? showPipAdView({
required BuildContext context,
required Map<String, dynamic> adData,
int? width,
int? height,
int? x,
int? y,
String? adLabelText,
String? adLabelAlignment,
void Function(Map? ad)? onAdClicked,
void Function(Map? ad, String? trackingId)? onAdAppeared,
required OsmosConfig config,
}) async {
// Cancel any previous subscription to prevent multiple listeners.
await _eventSubscription?.cancel(); // Prevent duplicate listeners
// Calculate dimensions using the same logic as widget-based ads
final dimensions = AdDimensionUtils.calculateDimensions(
context: context,
userWidth: width?.toDouble(),
userHeight: height?.toDouble(),
adData: adData,
);
final calculatedWidth = dimensions['width']!.toInt();
final calculatedHeight = dimensions['height']!.toInt();
// Start listening to broadcast events from the native side.
_eventSubscription = _eventChannel.receiveBroadcastStream().listen((event) {
if (event is Map && event.containsKey("event")) {
final eventName = event["event"];
if (eventName == AdEventConstants.onClick && onAdClicked != null) {
onAdClicked(event["adData"]);
} else if (eventName == AdEventConstants.onAppear &&
onAdAppeared != null) {
onAdAppeared(event["adData"], event["trackingId"]);
}
}
});
try {
// Invoke the native method to display the interstitial ad.
await MethodHandler.invokeNativeMethod(
'pipAdView',
arguments: {
'adData': adData,
'width': calculatedWidth,
'height': calculatedHeight,
'x': x,
'y': y,
'adLabelText': adLabelText,
'adLabelAlignment': adLabelAlignment,
},
);
} on OsmosException {
rethrow; // Re-throw OsmosException to maintain error context
} catch (e) {
throw OsmosException(
errorCode: OsmosErrorCodes.pipAdError,
details: 'Failed to show PIP ad: ${e.toString()}',
nativeError: e,
);
}
}