flutter_admobs_handler 1.1.8 copy "flutter_admobs_handler: ^1.1.8" to clipboard
flutter_admobs_handler: ^1.1.8 copied to clipboard

Reusable AdMob utilities for Flutter with banner, native advanced, app open, interstitial, rewarded, and rewarded interstitial ads, test/production switching, and a central AppAdsUtil configuration API.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter_admobs_handler/flutter_admobs_handler.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Defaults to Google test inventory. Set production unit IDs and
  // useTestAds = false before shipping.
  AppAdsUtil.instance.configure(useTestAds: true, onLog: debugPrint);

  await AppAdsUtil.instance.initializeAdsSdk();
  runApp(const ExampleApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'flutter_admobs_handler example',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigo),
        useMaterial3: true,
      ),
      home: const AdsDemoPage(),
    );
  }
}

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

  @override
  State<AdsDemoPage> createState() => _AdsDemoPageState();
}

class _AdsDemoPageState extends State<AdsDemoPage> {
  late final InterstitialAdUtil _interstitial;
  late final RewardedAdUtil _rewarded;
  late final RewardedInterstitialAdUtil _rewardedInterstitial;
  late final AppOpenAdUtil _appOpen;

  var _interstitialReady = false;
  var _rewardedReady = false;
  var _rewardedInterstitialReady = false;
  var _appOpenReady = false;
  var _isShowingFullscreen = false;
  String _status = 'Loading ads…';

  @override
  void initState() {
    super.initState();

    _interstitial = InterstitialAdUtil(
      adUnitIds: AppAdsUtil.instance.interstitialAdUnitIds,
      onLoaded: () =>
          _onAdLoaded(() => _interstitialReady = true, 'Interstitial ready'),
      onError: (error) => _onAdError(
        () => _interstitialReady = false,
        'Interstitial error: $error',
      ),
      onDismissed: () => _onAdDismissed(
        () => _interstitialReady = false,
        'Interstitial dismissed; reloading…',
      ),
    );

    _rewarded = RewardedAdUtil(
      adUnitIds: AppAdsUtil.instance.rewardedAdUnitIds,
      onLoaded: () =>
          _onAdLoaded(() => _rewardedReady = true, 'Rewarded ready'),
      onError: (error) =>
          _onAdError(() => _rewardedReady = false, 'Rewarded error: $error'),
      onDismissed: () => _onAdDismissed(
        () => _rewardedReady = false,
        'Rewarded dismissed; reloading…',
      ),
    );

    _rewardedInterstitial = RewardedInterstitialAdUtil(
      adUnitIds: AppAdsUtil.instance.rewardedInterstitialAdUnitIds,
      onLoaded: () => _onAdLoaded(
        () => _rewardedInterstitialReady = true,
        'Rewarded interstitial ready',
      ),
      onError: (error) => _onAdError(
        () => _rewardedInterstitialReady = false,
        'Rewarded interstitial error: $error',
      ),
      onDismissed: () => _onAdDismissed(
        () => _rewardedInterstitialReady = false,
        'Rewarded interstitial dismissed; reloading…',
      ),
    );

    _appOpen = AppOpenAdUtil(
      adUnitIds: AppAdsUtil.instance.appOpenAdUnitIds,
      onLoaded: () =>
          _onAdLoaded(() => _appOpenReady = true, 'App open ad ready'),
      onError: (error) =>
          _onAdError(() => _appOpenReady = false, 'App open error: $error'),
      onDismissed: () => _onAdDismissed(
        () => _appOpenReady = false,
        'App open dismissed; reloading…',
      ),
    );

    _preloadFullscreenAds();
  }

  void _onAdLoaded(VoidCallback markReady, String message) {
    if (!mounted) return;
    setState(() {
      markReady();
      _status = message;
    });
  }

  void _onAdError(VoidCallback markNotReady, String message) {
    if (!mounted) return;
    setState(() {
      markNotReady();
      _status = message;
    });
  }

  void _onAdDismissed(VoidCallback markNotReady, String message) {
    if (!mounted) return;
    setState(() {
      markNotReady();
      _status = message;
    });
  }

  Future<void> _preloadFullscreenAds() async {
    await Future.wait<bool>([
      _interstitial.load(),
      _rewarded.load(),
      _rewardedInterstitial.load(),
      _appOpen.load(),
    ]);
    if (!mounted) return;
    setState(() {
      _status =
          'Banner uses Google test units. Tap a button to show a fullscreen ad.';
    });
  }

  Future<void> _showInterstitial() async {
    if (_isShowingFullscreen || !_interstitial.isReady) {
      setState(() => _status = 'Interstitial is not ready yet');
      return;
    }

    setState(() {
      _isShowingFullscreen = true;
      _interstitialReady = false;
      _status = 'Showing interstitial…';
    });

    final shown = await _interstitial.show();
    if (!mounted) return;
    setState(() {
      _isShowingFullscreen = false;
      _status = shown ? 'Interstitial closed' : 'Interstitial failed to show';
    });
  }

  Future<void> _showRewarded() async {
    if (_isShowingFullscreen || !_rewarded.isReady) {
      setState(() => _status = 'Rewarded ad is not ready yet');
      return;
    }

    setState(() {
      _isShowingFullscreen = true;
      _rewardedReady = false;
      _status = 'Showing rewarded…';
    });

    final result = await _rewarded.show(
      onUserEarnedReward: (reward) {
        debugPrint('Reward callback: ${reward.amount} ${reward.type}');
      },
    );

    if (!mounted) return;
    setState(() {
      _isShowingFullscreen = false;
      _status = _rewardStatusMessage(result, 'Rewarded');
    });
  }

  Future<void> _showRewardedInterstitial() async {
    if (_isShowingFullscreen || !_rewardedInterstitial.isReady) {
      setState(() => _status = 'Rewarded interstitial is not ready yet');
      return;
    }

    setState(() {
      _isShowingFullscreen = true;
      _rewardedInterstitialReady = false;
      _status = 'Showing rewarded interstitial…';
    });

    final result = await _rewardedInterstitial.show(
      onUserEarnedReward: (reward) {
        debugPrint(
          'Rewarded interstitial callback: ${reward.amount} ${reward.type}',
        );
      },
    );

    if (!mounted) return;
    setState(() {
      _isShowingFullscreen = false;
      _status = _rewardStatusMessage(result, 'Rewarded interstitial');
    });
  }

  Future<void> _showAppOpen() async {
    if (_isShowingFullscreen || !_appOpen.isReady) {
      setState(() => _status = 'App open ad is not ready yet');
      return;
    }

    setState(() {
      _isShowingFullscreen = true;
      _appOpenReady = false;
      _status = 'Showing app open ad…';
    });

    final shown = await _appOpen.show();
    if (!mounted) return;
    setState(() {
      _isShowingFullscreen = false;
      _status = shown ? 'App open ad closed' : 'App open ad failed to show';
    });
  }

  String _rewardStatusMessage(RewardedAdShowResult result, String label) {
    if (!result.shown) {
      return '$label ad failed to show';
    }
    if (result.rewardEarned) {
      final reward = result.reward;
      return reward == null
          ? '$label reward earned'
          : '$label reward earned: ${reward.amount} ${reward.type}';
    }
    return '$label ad closed without earning a reward';
  }

  @override
  void dispose() {
    _interstitial.dispose();
    _rewarded.dispose();
    _rewardedInterstitial.dispose();
    _appOpen.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('AdMob Example')),
      body: Column(
        children: [
          Expanded(
            child: ListView(
              padding: const EdgeInsets.all(24),
              children: [
                Text(
                  'flutter_admobs_handler',
                  style: Theme.of(context).textTheme.headlineSmall,
                ),
                const SizedBox(height: 8),
                Text(
                  'Demonstrates banner, native advanced, app open, interstitial, '
                  'rewarded, and rewarded interstitial ads with '
                  'RewardedAdShowResult from Google test inventory.',
                  style: Theme.of(context).textTheme.bodyMedium,
                ),
                const SizedBox(height: 24),
                Text(_status),
                const SizedBox(height: 24),
                const Text('Native advanced (medium template)'),
                const SizedBox(height: 8),
                const AdMobNativeWidget(templateType: TemplateType.medium),
                const SizedBox(height: 24),
                FilledButton(
                  onPressed: _interstitialReady && !_isShowingFullscreen
                      ? _showInterstitial
                      : null,
                  child: Text(
                    _interstitialReady
                        ? 'Show interstitial'
                        : 'Loading interstitial…',
                  ),
                ),
                const SizedBox(height: 12),
                FilledButton.tonal(
                  onPressed: _appOpenReady && !_isShowingFullscreen
                      ? _showAppOpen
                      : null,
                  child: Text(
                    _appOpenReady ? 'Show app open' : 'Loading app open…',
                  ),
                ),
                const SizedBox(height: 12),
                FilledButton.tonal(
                  onPressed: _rewardedReady && !_isShowingFullscreen
                      ? _showRewarded
                      : null,
                  child: Text(
                    _rewardedReady ? 'Show rewarded' : 'Loading rewarded…',
                  ),
                ),
                const SizedBox(height: 12),
                FilledButton.tonal(
                  onPressed: _rewardedInterstitialReady && !_isShowingFullscreen
                      ? _showRewardedInterstitial
                      : null,
                  child: Text(
                    _rewardedInterstitialReady
                        ? 'Show rewarded interstitial'
                        : 'Loading rewarded interstitial…',
                  ),
                ),
              ],
            ),
          ),
          const AdMobBannerWidget(useAdaptiveWidth: true),
        ],
      ),
    );
  }
}
2
likes
145
points
264
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Reusable AdMob utilities for Flutter with banner, native advanced, app open, interstitial, rewarded, and rewarded interstitial ads, test/production switching, and a central AppAdsUtil configuration API.

Topics

#admob #ads #advertising #google-mobile-ads #monetization

License

MIT (license)

Dependencies

flutter, google_mobile_ads

More

Packages that depend on flutter_admobs_handler