showInterstitialAdView 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.alignment(String): Alignment of the ad on screen (default is"CENTER").adLabelText(String): Text of the ad Label on ad.adLabelAlignment(String): Alignment of the ad Label on ad (default is"topLeading").x(int): X-axis offset for custom ad positioning (default is0).y(int): Y-axis offset for custom ad positioning (default is0).onAdClicked(void Function(Map? ad)?): Optional callback triggered when the ad is clicked.onAdAppeared(void Function(Map? ad)?): Optional callback triggered when the ad appears.
Returns: Future<void> .
Implementation
Future<void>? showInterstitialAdView({
required BuildContext context,
required Map<String, dynamic> adData,
int? width,
int? height,
String? alignment,
String? adLabelText,
String? adLabelAlignment,
int? x,
int? y,
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(
'interstitialAdView',
arguments: {
'adData': adData,
'width': calculatedWidth,
'height': calculatedHeight,
'alignment': alignment,
'adLabelText': adLabelText,
'adLabelAlignment': adLabelAlignment,
'x': x,
'y': y,
},
);
} on OsmosException {
rethrow; // Re-throw OsmosException to maintain error context
} catch (e) {
throw OsmosException(
errorCode: OsmosErrorCodes.interstitialAdError,
details: 'Failed to show interstitial ad: ${e.toString()}',
nativeError: e,
);
}
}