Examples
Ready-to-adapt examples for each ad format. They assume the SDK is already initialized (see Getting Started). Replace the placeholder IDs with your own.
๐ฏ Banner Ad Exampleโ
import 'package:flutter/material.dart';
import 'package:ocm_ads/ocm_ads.dart';
class BannerExample extends StatefulWidget {
const BannerExample({super.key});
State<BannerExample> createState() => _BannerExampleState();
}
class _BannerExampleState extends State<BannerExample> {
bool _failed = false;
Widget build(BuildContext context) {
if (_failed) return const SizedBox.shrink();
return Center(
child: OcmBannerView(
configId: 'your-banner-config-id', // an ad unit id from your OcmConfig
width: 300,
height: 250,
onAdLoaded: () => debugPrint('Banner loaded'),
onAdFailed: (OcmAdError error) {
debugPrint('Banner failed: ${error.message}');
setState(() => _failed = true);
},
onAdClicked: () => debugPrint('Banner clicked'),
onImpression: () => debugPrint('Banner impression'),
),
);
}
}
๐ฌ Interstitial Ad Exampleโ
Load an interstitial, keep the returned object, show it when ready, and dispose it when you're done.
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:ocm_ads/ocm_ads.dart';
class MyInterstitialListener extends OcmInterstitialListener {
const MyInterstitialListener();
void onLoaded() => debugPrint('Interstitial loaded');
void onFailedToLoad(OcmAdError error) =>
debugPrint('Interstitial failed: ${error.message}');
void onShown() => debugPrint('Interstitial shown');
void onClosed() => debugPrint('Interstitial closed');
void onClicked() => debugPrint('Interstitial clicked');
}
OcmInterstitialAd? interstitialAd;
Future<void> loadInterstitial() async {
try {
interstitialAd = await OcmInterstitialAd.load(
prebidConfigId: 'your-interstitial-config-id',
gamAdUnitId: '/75351959/testadunit/test_app_interstitial',
fetchTimeout: const Duration(seconds: 5),
listener: const MyInterstitialListener(),
);
} on PlatformException catch (error) {
debugPrint('Interstitial load error: ${error.code} ${error.message}');
}
}
Future<void> showInterstitial() async {
final ad = interstitialAd;
if (ad == null) return;
if (await ad.isReady()) {
await ad.show();
}
}
Future<void> disposeInterstitial() async {
await interstitialAd?.dispose();
interstitialAd = null;
}
๐ Rewarded Ad Exampleโ
Load rewarded ads with a Google Mobile Ads ad unit ID. Apply server-side verification before showing if your reward flow needs it.
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:ocm_ads/ocm_ads.dart';
// Google's rewarded test ad units differ per platform.
final rewardedAdUnitId = defaultTargetPlatform == TargetPlatform.iOS
? 'ca-app-pub-3940256099942544/1712485313'
: 'ca-app-pub-3940256099942544/5224354917';
class MyRewardedListener extends OcmRewardedListener {
const MyRewardedListener();
void onLoaded() => debugPrint('Rewarded ad loaded');
void onFailedToLoad(OcmAdError error) =>
debugPrint('Rewarded ad failed: ${error.message}');
void onShowFailed(OcmAdError error) =>
debugPrint('Rewarded ad failed to show: ${error.message}');
void onDisplayed() => debugPrint('Rewarded ad displayed');
void onDismissed() => debugPrint('Rewarded ad dismissed');
void onUserEarnedReward(OcmRewardedResult reward) {
debugPrint('Reward earned: ${reward.rewardAmount} ${reward.rewardType}');
}
}
OcmRewardedAd? rewardedAd;
Future<void> loadRewarded() async {
rewardedAd = await OcmRewardedAd.load(
adUnitId: rewardedAdUnitId,
listener: const MyRewardedListener(),
);
}
Future<void> showRewarded() async {
final ad = rewardedAd;
if (ad == null) return;
try {
// Optional: only if you use server-side verification.
await ad.applyServerSideVerification(
userId: 'current-user-id',
customData: 'optional-custom-data',
);
await ad.show();
} on PlatformException catch (error) {
debugPrint('Rewarded show error: ${error.code} ${error.message}');
}
}
Future<void> disposeRewarded() async {
await rewardedAd?.dispose();
rewardedAd = null;
}
๐ฑ Native Ad View Exampleโ
OcmNativeAdView renders the native placement and registers impression and click tracking on both platforms. On Android, omit height to size the view to the rendered ad; an explicit height keeps the view at that size. On iOS, give it a height.
GAM modeโ
Configure the Prebid custom native format in Google Ad Manager and pass its format ID:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:ocm_ads/ocm_ads.dart';
OcmNativeAdView(
prebidConfigId: 'your-native-config-id',
gamAdUnitId: '/75351959/testadunit/test_app_native',
gamNativeFormatId: 'your-gam-native-format-id',
mode: OcmNativeLoadMode.gam,
width: 320,
height: defaultTargetPlatform == TargetPlatform.iOS ? 400 : null,
onAdLoaded: () => debugPrint('Native view loaded'),
onAdFailed: (OcmAdError error) =>
debugPrint('Native view failed: ${error.message}'),
);
Direct Prebid modeโ
For direct Prebid native demand, omit the GAM IDs:
OcmNativeAdView(
prebidConfigId: 'your-native-config-id',
mode: OcmNativeLoadMode.prebid,
width: 320,
height: defaultTargetPlatform == TargetPlatform.iOS ? 400 : null,
);
๐งพ Native Ad Data Loader (Android only)โ
OcmNativeAdLoader returns the native ad's assets on Android, for inspection. It doesn't register impression or click tracking, so use OcmNativeAdView for ads shown to users. On iOS, load throws unsupported_platform.
import 'package:flutter/foundation.dart';
import 'package:ocm_ads/ocm_ads.dart';
class MyNativeListener extends OcmNativeListener {
const MyNativeListener();
void onLoaded(OcmNativeAd ad) =>
debugPrint('Native ad loaded: ${ad.title ?? 'no title'}');
void onFailedToLoad(OcmAdError error) =>
debugPrint('Native ad failed: ${error.message}');
}
Future<OcmNativeAd> loadNativeAd() {
return const OcmNativeAdLoader(listener: MyNativeListener()).load(
prebidConfigId: 'your-native-config-id',
gamAdUnitId: '/75351959/testadunit/test_app_native',
gamNativeFormatId: 'your-gam-native-format-id',
);
}
The returned OcmNativeAd has title, body, publisherCompany, callToAction, imageUrl, iconUrl, videoUrl, and layoutType, any of which may be null.
Best Practicesโ
1. Dispose Full-Screen Adsโ
Dispose interstitial and rewarded ads when the owning widget or service is destroyed:
void dispose() {
interstitialAd?.dispose();
rewardedAd?.dispose();
super.dispose();
}
2. Catch Platform Errorsโ
Load and show methods can throw PlatformException. See Error Handling for the error codes.
import 'package:flutter/services.dart';
try {
await loadInterstitial();
} on PlatformException catch (error) {
debugPrint('Platform error: ${error.code} ${error.message}');
} catch (error) {
debugPrint('Unexpected error: $error');
}
3. Keep Debugging Off in Productionโ
setPrebidDebug and setPbsEventLogging are for testing only. See Debugging.
๐ Supportโ
For support and documentation, contact us at [email protected]