Getting Started
🚀 Quick Start​
This guide will help you display your first ad in a Flutter app.
Step 1: Import the Plugin​
import 'package:ocm_ads/ocm_ads.dart';
Step 2: Initialize the SDK​
Build the SDK config in your app and pass it to OcmFlutterPlugin.initializeWithConfig once, before showing any ad. List every banner ad unit the app will load in adUnits: OcmBannerView looks its configId up there.
import 'package:flutter/material.dart';
import 'package:ocm_ads/ocm_ads.dart';
const ocmConfig = OcmConfig(
adUnits: <OcmAdUnit>[
OcmAdUnit(
id: 'your-banner-config-id', // also passed to OcmBannerView's configId
format: 'banner',
size: '300x250',
position: 'custom',
refresh: 30,
renderMode: OcmRenderMode.prebidGam,
),
],
gam: OcmGamConfig(
networkCode: '75351959',
adUnitPath: '/75351959/testadunit/test_app_300x250',
),
privacy: OcmPrivacyConfig(gdpr: 0, ccpa: '1---', coppa: 0),
);
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await OcmFlutterPlugin.initializeWithConfig(
ocmConfig,
prebidAccountId: 'your-prebid-account-id',
);
runApp(const MyApp());
}
prebidAccountId on AndroidprebidAccountId is required on Android: without it, initializeWithConfig throws a PlatformException with code missing_argument. On iOS it's optional, but Prebid is skipped when it's omitted, so always pass it.
The examples use test privacy values (gdpr: 0). The SDK reads privacy at initialization, so in production get GDPR applicability and consent from your consent management platform first and build privacy from it. See Privacy.
You can also initialize with an OCM publisher ID and let the SDK fetch the ad unit configuration remotely. See initialize().
Step 3: Display a Banner Ad​
Give OcmBannerView the ad unit id from your config and an explicit size. The ad loads when the widget is built.
import 'package:flutter/material.dart';
import 'package:ocm_ads/ocm_ads.dart';
class BannerSlot extends StatelessWidget {
const BannerSlot({super.key});
Widget build(BuildContext context) {
return Center(
child: OcmBannerView(
configId: 'your-banner-config-id',
width: 300,
height: 250,
onAdLoaded: () => debugPrint('Banner loaded'),
onAdFailed: (OcmAdError error) {
debugPrint('Banner failed: ${error.code} ${error.message}');
},
onAdClicked: () => debugPrint('Banner clicked'),
onImpression: () => debugPrint('Banner impression'),
),
);
}
}
🎯 Complete Example​
Here's a complete screen with a banner, an interstitial, and a rewarded ad. Replace the placeholder IDs with your own; the rewarded ad units are Google's public test IDs.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:ocm_ads/ocm_ads.dart';
const bannerConfigId = 'your-banner-config-id';
const interstitialPrebidConfigId = 'your-interstitial-config-id';
const interstitialGamAdUnitId = '/75351959/testadunit/test_app_interstitial';
// Google's rewarded test ad units differ per platform.
final rewardedAdUnitId = defaultTargetPlatform == TargetPlatform.iOS
? 'ca-app-pub-3940256099942544/1712485313'
: 'ca-app-pub-3940256099942544/5224354917';
const ocmConfig = OcmConfig(
adUnits: <OcmAdUnit>[
OcmAdUnit(
id: bannerConfigId,
format: 'banner',
size: '300x250',
position: 'custom',
refresh: 30,
),
],
gam: OcmGamConfig(
networkCode: '75351959',
adUnitPath: '/75351959/testadunit/test_app_300x250',
),
privacy: OcmPrivacyConfig(gdpr: 0, ccpa: '1---', coppa: 0),
);
void main() => runApp(const MaterialApp(home: AdsScreen()));
class AdsScreen extends StatefulWidget {
const AdsScreen({super.key});
State<AdsScreen> createState() => _AdsScreenState();
}
class _AdsScreenState extends State<AdsScreen> {
bool _ready = false;
OcmInterstitialAd? _interstitial;
OcmRewardedAd? _rewarded;
void initState() {
super.initState();
_initialize();
}
Future<void> _initialize() async {
try {
await OcmFlutterPlugin.initializeWithConfig(
ocmConfig,
prebidAccountId: 'your-prebid-account-id',
);
if (mounted) setState(() => _ready = true);
} on PlatformException catch (error) {
debugPrint('OCM init failed: ${error.code} ${error.message}');
}
}
Future<void> _loadInterstitial() async {
try {
await _interstitial?.dispose();
final ad = await OcmInterstitialAd.load(
prebidConfigId: interstitialPrebidConfigId,
gamAdUnitId: interstitialGamAdUnitId,
fetchTimeout: const Duration(seconds: 5),
listener: _InterstitialListener(),
);
_interstitial = ad;
} on PlatformException catch (error) {
debugPrint('Interstitial error: ${error.code} ${error.message}');
}
}
Future<void> _showRewarded() async {
try {
await _rewarded?.dispose();
_rewarded = await OcmRewardedAd.load(
adUnitId: rewardedAdUnitId,
// Show as soon as the ad has loaded.
listener: _RewardedListener(onReady: () => _rewarded?.show()),
);
} on PlatformException catch (error) {
debugPrint('Rewarded error: ${error.code} ${error.message}');
}
}
void dispose() {
_interstitial?.dispose();
_rewarded?.dispose();
super.dispose();
}
Widget build(BuildContext context) {
if (!_ready) {
return const Scaffold(body: Center(child: CircularProgressIndicator()));
}
return Scaffold(
appBar: AppBar(title: const Text('OCM Ads')),
body: ListView(
padding: const EdgeInsets.all(16),
children: <Widget>[
const Center(
child: OcmBannerView(configId: bannerConfigId, width: 300, height: 250),
),
const SizedBox(height: 16),
FilledButton(
onPressed: _loadInterstitial,
child: const Text('Load interstitial'),
),
FilledButton(
onPressed: () async {
final ad = _interstitial;
if (ad != null && await ad.isReady()) await ad.show();
},
child: const Text('Show interstitial'),
),
FilledButton(
onPressed: _showRewarded,
child: const Text('Show rewarded ad'),
),
],
),
);
}
}
class _InterstitialListener extends OcmInterstitialListener {
void onLoaded() => debugPrint('Interstitial loaded');
void onFailedToLoad(OcmAdError error) =>
debugPrint('Interstitial failed: ${error.message}');
void onClosed() => debugPrint('Interstitial closed');
}
class _RewardedListener extends OcmRewardedListener {
_RewardedListener({required this.onReady});
final VoidCallback onReady;
void onLoaded() => onReady();
void onFailedToLoad(OcmAdError error) =>
debugPrint('Rewarded failed: ${error.message}');
void onUserEarnedReward(OcmRewardedResult reward) {
debugPrint('User earned ${reward.rewardAmount} ${reward.rewardType}');
}
}
📡 Ad Events​
Banners report events through callbacks on OcmBannerView:
| Callback | Description |
|---|---|
onAdLoaded | Ad successfully loaded |
onAdFailed | Ad failed to load; receives an OcmAdError |
onAdClicked | User tapped the ad |
onImpression | Ad impression recorded |
Interstitial, rewarded, and native loader events go to listener classes. See Examples.
Best Practices​
1. Initialize Early​
Initialize once at startup, before the first ad request, and wait for the Future to complete before showing ads.
2. Handle Errors​
Load and show methods can throw PlatformException. Catch it and carry on without an ad:
import 'package:flutter/services.dart';
try {
await ad.show();
} on PlatformException catch (error) {
debugPrint('Ad error: ${error.code} ${error.message}');
}
3. Dispose Full-Screen Ads​
Call dispose() on interstitial and rewarded ads when the owning widget or service goes away.
Next Steps​
- Learn about Configuration options
- Explore the API Reference
- Check out complete Examples