Skip to main content

ocm_ads 0.0.4 copy "ocm_ads: ^0.0.4" to clipboard
ocm_ads: ^0.0.4 copied to clipboard

Flutter bindings for the OCM AdNetwork SDK, supporting initialization and banner, interstitial, rewarded, and native ad formats on Android and iOS.

example/lib/main.dart

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:ocm_ads/ocm_ads.dart';

void main() {
  runApp(const OcmExampleApp());
}

class OcmExampleApp extends StatelessWidget {
  const OcmExampleApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepOrange),
      ),
      home: const OcmExampleScreen(),
    );
  }
}

class OcmExampleScreen extends StatefulWidget {
  const OcmExampleScreen({super.key});

  @override
  State<OcmExampleScreen> createState() => _OcmExampleScreenState();
}

class _OcmExampleScreenState extends State<OcmExampleScreen> {
  static const _prebidAccountId = 'X_FLUTTER';
  // PBS Admin stored request: banner_ocmdsp.
  static const _bannerConfigId = '48adb9a60bb1eb05';
  static const _rewardedAdUnitId = 'ca-app-pub-3940256099942544/5224354917';
  static const _interstitialPrebidConfigId = '1001-sreq-test-inters';
  static const _interstitialGamAdUnitId =
      '75351959/testadunit/test_app_interstitial';
  // Native HB placement used by the iOS and Android SDK example apps.
  static const _nativePrebidConfigId = '48adb9a60bb1eb05';

  final List<String> _events = <String>[];
  OcmInterstitialAd? _interstitialAd;
  OcmRewardedAd? _rewardedAd;
  OcmNativeAd? _nativeAd;
  bool _prebidDebug = true;
  bool _initialized = false;
  bool _showBanner = false;
  bool _showNativeView = false;

  OcmConfig get _localConfig {
    return const OcmConfig(
      adUnits: <OcmAdUnit>[
        OcmAdUnit(
          id: _bannerConfigId,
          format: 'banner',
          size: '300x250',
          position: 'custom',
          refresh: 0,
          renderMode: OcmRenderMode.prebid,
        ),
      ],
      gam: OcmGamConfig(
        networkCode: '75351959',
        adUnitPath: '/75351959/testadunit/test_app_320x50',
      ),
      privacy: OcmPrivacyConfig(gdpr: 0, ccpa: '1---', coppa: 0),
    );
  }

  @override
  void dispose() {
    _interstitialAd?.dispose();
    _rewardedAd?.dispose();
    super.dispose();
  }

  Future<void> _run(String label, Future<void> Function() action) async {
    try {
      await action();
      _log('$label: ok');
    } on PlatformException catch (error) {
      _log('$label: ${error.code} ${error.message}');
    } catch (error) {
      _log('$label: $error');
    }
  }

  void _log(String message) {
    setState(() {
      _events.insert(0, '${DateTime.now().toIso8601String()}  $message');
    });
  }

  Future<void> _initialize() {
    return _run('initializeWithConfig', () async {
      await OcmFlutterPlugin.setPrebidDebug(_prebidDebug);
      await OcmFlutterPlugin.setPbsEventLogging(true);
      await OcmFlutterPlugin.initializeWithConfig(
        _localConfig,
        prebidAccountId: _prebidAccountId,
      );
      setState(() => _initialized = true);
    });
  }

  bool _requireInitialized(String label) {
    if (_initialized) {
      return true;
    }
    _log('$label: initialize first');
    return false;
  }

  Future<void> _toggleDebug(bool enabled) async {
    await _run('setPrebidDebug', () async {
      await OcmFlutterPlugin.setPrebidDebug(enabled);
      setState(() => _prebidDebug = enabled);
    });
  }

  Future<void> _loadInterstitial() {
    return _run('load interstitial', () async {
      if (!_requireInitialized('load interstitial')) {
        return;
      }
      _interstitialAd = await OcmInterstitialAd.load(
        prebidConfigId: _interstitialPrebidConfigId,
        gamAdUnitId: _interstitialGamAdUnitId,
        listener: _ExampleInterstitialListener(_log),
      );
    });
  }

  Future<void> _showInterstitial() {
    return _run('show interstitial', () async {
      if (!_requireInitialized('show interstitial')) {
        return;
      }
      final ad = _interstitialAd;
      if (ad == null) {
        _log('show interstitial: load an ad first');
        return;
      }
      _log('interstitial ready: ${await ad.isReady()}');
      await ad.show();
    });
  }

  Future<void> _loadRewarded() {
    return _run('load rewarded', () async {
      if (!_requireInitialized('load rewarded')) {
        return;
      }
      _rewardedAd = await OcmRewardedAd.load(
        adUnitId: _rewardedAdUnitId,
        listener: _ExampleRewardedListener(_log),
      );
    });
  }

  Future<void> _showRewarded() {
    return _run('show rewarded', () async {
      if (!_requireInitialized('show rewarded')) {
        return;
      }
      final ad = _rewardedAd;
      if (ad == null) {
        _log('show rewarded: load an ad first');
        return;
      }
      await ad.show();
    });
  }

  Future<void> _loadNative() {
    return _run('load native', () async {
      if (!_requireInitialized('load native')) {
        return;
      }
      final ad = await OcmNativeAdLoader(listener: _ExampleNativeListener(_log))
          .load(
            prebidConfigId: _nativePrebidConfigId,
            mode: OcmNativeLoadMode.prebid,
          );
      setState(() => _nativeAd = ad);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('OCM AdNetwork Example')),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: <Widget>[
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children: <Widget>[
              FilledButton(
                onPressed: _initialize,
                child: const Text('Initialize'),
              ),
              FilterChip(
                selected: _prebidDebug,
                label: const Text('Prebid debug'),
                onSelected: _toggleDebug,
              ),
              FilterChip(
                selected: _showBanner,
                label: const Text('Banner'),
                onSelected: (selected) {
                  if (!_requireInitialized('banner')) {
                    return;
                  }
                  setState(() => _showBanner = selected);
                },
              ),
              FilterChip(
                selected: _showNativeView,
                label: const Text('Native HB view'),
                onSelected: (selected) {
                  if (!_requireInitialized('native view')) {
                    return;
                  }
                  setState(() => _showNativeView = selected);
                },
              ),
              FilledButton.tonal(
                onPressed: _loadInterstitial,
                child: const Text('Load interstitial'),
              ),
              FilledButton.tonal(
                onPressed: _showInterstitial,
                child: const Text('Show interstitial'),
              ),
              FilledButton.tonal(
                onPressed: _loadRewarded,
                child: const Text('Load rewarded'),
              ),
              FilledButton.tonal(
                onPressed: _showRewarded,
                child: const Text('Show rewarded'),
              ),
              FilledButton.tonal(
                onPressed: _loadNative,
                child: const Text('Load native data'),
              ),
            ],
          ),
          const SizedBox(height: 16),
          if (_showBanner)
            Center(
              child: OcmBannerView(
                configId: _bannerConfigId,
                width: 300,
                height: 250,
                onAdLoaded: () => _log('banner loaded'),
                onAdFailed: (error) => _log('banner failed: ${error.message}'),
                onAdClicked: () => _log('banner clicked'),
                onImpression: () => _log('banner impression'),
              ),
            ),
          const SizedBox(height: 16),
          if (_nativeAd != null) _NativeAdPanel(ad: _nativeAd!),
          if (_showNativeView)
            Padding(
              padding: const EdgeInsets.only(top: 16),
              child: OcmNativeAdView(
                prebidConfigId: _nativePrebidConfigId,
                mode: OcmNativeLoadMode.prebid,
                width: 320,
                height: defaultTargetPlatform == TargetPlatform.iOS
                    ? 400
                    : null,
                onAdLoaded: () => _log('native HB view loaded'),
                onAdFailed: (error) =>
                    _log('native HB view failed: ${error.message}'),
              ),
            ),
          const SizedBox(height: 16),
          Text('Events', style: Theme.of(context).textTheme.titleMedium),
          const SizedBox(height: 8),
          for (final event in _events)
            Padding(
              padding: const EdgeInsets.only(bottom: 6),
              child: Text(event),
            ),
        ],
      ),
    );
  }
}

class _NativeAdPanel extends StatelessWidget {
  const _NativeAdPanel({required this.ad});

  final OcmNativeAd ad;

  @override
  Widget build(BuildContext context) {
    return DecoratedBox(
      decoration: BoxDecoration(
        border: Border.all(color: Theme.of(context).colorScheme.outlineVariant),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(ad.title ?? 'Untitled native ad'),
            if (ad.body != null) Text(ad.body!),
            if (ad.publisherCompany != null) Text(ad.publisherCompany!),
            if (ad.callToAction != null) Text(ad.callToAction!),
            if (ad.imageUrl != null) Text('Image: ${ad.imageUrl}'),
            if (ad.iconUrl != null) Text('Icon: ${ad.iconUrl}'),
            if (ad.videoUrl != null) Text('Video: ${ad.videoUrl}'),
            if (ad.layoutType != null) Text('Layout: ${ad.layoutType}'),
          ],
        ),
      ),
    );
  }
}

class _ExampleInterstitialListener extends OcmInterstitialListener {
  const _ExampleInterstitialListener(this.log);

  final ValueChanged<String> log;

  @override
  void onLoaded() => log('interstitial loaded');

  @override
  void onFailedToLoad(OcmAdError error) {
    log('interstitial failed: ${error.message}');
  }

  @override
  void onShown() => log('interstitial shown');

  @override
  void onClosed() => log('interstitial closed');

  @override
  void onClicked() => log('interstitial clicked');
}

class _ExampleRewardedListener extends OcmRewardedListener {
  const _ExampleRewardedListener(this.log);

  final ValueChanged<String> log;

  @override
  void onLoaded() => log('rewarded loaded');

  @override
  void onFailedToLoad(OcmAdError error) =>
      log('rewarded failed: ${error.message}');

  @override
  void onShowFailed(OcmAdError error) {
    log('rewarded show failed: ${error.message}');
  }

  @override
  void onDisplayed() => log('rewarded displayed');

  @override
  void onDismissed() => log('rewarded dismissed');

  @override
  void onUserEarnedReward(OcmRewardedResult reward) {
    log('rewarded earned: ${reward.rewardAmount} ${reward.rewardType}');
  }
}

class _ExampleNativeListener extends OcmNativeListener {
  const _ExampleNativeListener(this.log);

  final ValueChanged<String> log;

  @override
  void onLoaded(OcmNativeAd ad) =>
      log('native loaded: ${ad.title ?? 'no title'}');

  @override
  void onFailedToLoad(OcmAdError error) =>
      log('native failed: ${error.message}');
}
0
likes
150
points
--
downloads

Documentation

API reference

Publisher

verified publisherorangeclickmedia.com

Flutter bindings for the OCM AdNetwork SDK, supporting initialization and banner, interstitial, rewarded, and native ad formats on Android and iOS.

Homepage

Topics

#ads #advertising #monetization #prebid #google-ad-manager

License

MIT (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on ocm_ads

Packages that implement ocm_ads