google_admob_sdk 1.0.5
google_admob_sdk: ^1.0.5 copied to clipboard
A self-managed, high-speed Flutter plugin for Google Mobile Ads Next-Gen SDK & 3rd-Party Ad Networks (AppLovin, Meta, Mintegral, Unity Ads, Pangle, IronSource, Liftoff) with centralized Ad Unit ID man [...]
example/lib/main.dart
import 'package:flutter/material.dart';
import 'package:google_admob_sdk/google_admob_sdk.dart';
import 'ad_test_config.dart';
import 'mediation_test_panel.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Initialize Firebase if google-services.json / GoogleService-Info.plist is configured
try {
await Firebase.initializeApp();
} catch (e) {
debugPrint('Firebase not configured in example (skipping): $e');
}
// Initialize SDK with the IDs from ads.local.json (Google's sample units without it)
// and the mediation setup.
final initStatus = await GoogleAdmobSdk.initialize(
config: ExampleAdConfig.adIds,
// Test devices get test ads from AdMob and can open Ad Inspector, whose
// "Single ad source testing" forces one mediation network to serve.
testDeviceIds: ExampleAdConfig.testDeviceIds,
// Meta Audience Network serves test ads; other networks need test devices
// registered in their dashboards (see README.md).
mediationConfig: const MediationConfig(
enableTestMode: true,
enabledNetworks: [
ThirdPartyAdNetwork.applovin,
ThirdPartyAdNetwork.meta,
ThirdPartyAdNetwork.mintegral,
ThirdPartyAdNetwork.unity,
ThirdPartyAdNetwork.pangle,
ThirdPartyAdNetwork.ironSource,
ThirdPartyAdNetwork.liftoff,
],
preloadBiddingSignals: true,
),
// The App ID comes from the manifest / Info.plist (ADMOB_ANDROID_APP_ID, ADMOB_IOS_APP_ID).
initializationConfig: const InitializationConfig(
waitForAdapterInitialization: true,
),
logger: FirebaseAdLogger(),
enableLogging: true,
enableDeviceLog: true,
maxAdContentRating: MaxAdContentRating.g,
ageRestrictedTreatment: TagForChildDirectedTreatment.no,
);
runApp(MyApp(adapterStatuses: initStatus.adapterStatuses));
}
/// Demo modes for showcasing Native Ad capabilities
enum NativeDemoType { presetMediaView, presetCls, customStyle, customLayout }
class MyApp extends StatefulWidget {
const MyApp({super.key, this.adapterStatuses = const {}});
/// Mediation adapter statuses returned by [GoogleAdmobSdk.initialize].
final Map<String, AdapterStatus> adapterStatuses;
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late final AppLifecycleReactor _lifecycleReactor;
NativeDemoType _selectedNativeType = NativeDemoType.presetMediaView;
bool _isCustomLayoutDismissed = false;
bool _useCollapsibleAdaptiveBanner = true;
final List<AdLoadLogEntry> _adLoads = [];
// Unmounts banner/native widgets while their pools are cleared on reload.
bool _adWidgetsSuspended = false;
@override
void initState() {
super.initState();
// Record which ad source (AdMob or a mediation network) served each request
AdInstanceManager.instance.onAdLoadResult = (ad, error) {
if (!mounted) return;
setState(() {
_adLoads.insert(0, AdLoadLogEntry(ad, error));
if (_adLoads.length > 10) _adLoads.removeLast();
});
};
_loadFullScreenAds();
// Initialize AppLifecycleReactor to automatically show App Open ads on return from background
_lifecycleReactor = AppLifecycleReactor(
appOpenAdManager: AppOpenAdManager.shared,
minBackgroundDuration: const Duration(seconds: 15),
minShowInterval: const Duration(minutes: 5),
)..listenToAppStateChanges();
}
void _loadFullScreenAds() {
// Preload ads using shared singleton managers with custom placement keys (adKey)
InterstitialAdManager.shared.loadAd(
adKey: 'level_complete_interstitial',
screenName: 'scrLevelComplete',
adPlacement: 'scrLevelComplete',
);
RewardedAdManager.shared.loadAd(
adKey: 'extra_lives_rewarded',
screenName: 'scrShop',
adPlacement: 'scrShop',
serverSideVerificationOptions: const ServerSideVerificationOptions(
userId: 'demo_user_1',
customData: 'demo_extra_lives',
),
);
AppOpenAdManager.shared.loadAd(
adKey: 'app_launch_open_ad',
screenName: 'scrSplash',
adPlacement: 'scrSplash',
);
}
/// Drops every cached ad and requests new ones, so a network picked in
/// Ad Inspector's "Single ad source testing" serves the next requests.
Future<void> _reloadAllAds() async {
setState(() => _adWidgetsSuspended = true);
await WidgetsBinding.instance.endOfFrame;
BannerAdPool.clear();
NativeAdPool.clear();
InterstitialAdManager.shared.dispose();
RewardedAdManager.shared.dispose();
AppOpenAdManager.shared.dispose();
_loadFullScreenAds();
if (mounted) setState(() => _adWidgetsSuspended = false);
}
void _openAdInspector(BuildContext context) {
GoogleAdmobSdk.openAdInspector(
onClosed: (error) {
if (!context.mounted) return;
if (error != null) {
// Ad Inspector only opens on test devices (ADMOB_TEST_DEVICE_IDS,
// emulators, or devices added in AdMob > Settings > Test devices).
_showMessage(context, 'Ad Inspector error: $error');
return;
}
_reloadAllAds();
},
);
}
@override
void dispose() {
AdInstanceManager.instance.onAdLoadResult = null;
_lifecycleReactor.dispose();
super.dispose();
}
void _showMessage(BuildContext context, String message) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(message)));
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Google AdMob SDK Demo'),
centerTitle: true,
),
body: Builder(
builder: (context) {
return Column(
children: [
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'Ad Mobility Showcase',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
const Text(
'Demonstrates Banner, Interstitial (Safe Show & Cooldown), Rewarded (Shared Singleton), App Open, and Native ads with Databuckets tracking.',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.grey),
),
const SizedBox(height: 16),
// Mediation diagnostics: Ad Inspector, adapter statuses, winning ad source per request
MediationTestPanel(
adapterStatuses: widget.adapterStatuses,
adLoads: _adLoads,
onOpenAdInspector: () => _openAdInspector(context),
onReloadAds: _reloadAllAds,
),
const SizedBox(height: 24),
// App Open Ad Button
ElevatedButton.icon(
icon: const Icon(Icons.open_in_new),
label: const Text('Show App Open Ad'),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 14),
),
onPressed: () async {
if (AppOpenAdManager.shared.isAdAvailable) {
await AppOpenAdManager.shared.showAdIfAvailable(
adKey: 'app_launch_open_ad',
);
} else {
_showMessage(
context,
'App Open Ad is loading...',
);
AppOpenAdManager.shared.loadAd(
adKey: 'app_launch_open_ad',
);
}
},
),
const SizedBox(height: 12),
// Interstitial Ad Button (Safe Show with Cooldown & Countdown)
ElevatedButton.icon(
icon: const Icon(Icons.fullscreen),
label: const Text(
'Show Interstitial Safely (Cooldown & Warning)',
),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 14),
),
onPressed: () async {
final success = await InterstitialAdManager.shared
.showAdSafely(
context: context,
adKey: 'level_complete_interstitial',
checkCooldown: true,
showWarningCountdown: true,
onCompleted: () {
_showMessage(
context,
'Interstitial completed / dismissed',
);
},
);
if (!success &&
InterstitialAdManager.shared.isAdLoaded &&
!InterstitialAdManager.shared.canShow) {
final seconds = InterstitialAdManager
.shared
.remainingCooldown
.inSeconds;
if (context.mounted) {
_showMessage(
context,
'⏳ In cooldown: please wait another ${seconds}s',
);
}
}
},
),
const SizedBox(height: 12),
// Rewarded Ad Button (Shared Singleton)
ElevatedButton.icon(
icon: const Icon(Icons.card_giftcard),
label: const Text(
'Show Rewarded Ad (Shared Singleton)',
),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 14),
),
onPressed: () async {
await RewardedAdManager.shared.showAdSafely(
context: context,
adKey: 'extra_lives_rewarded',
onUserEarnedReward: (ad, reward) {
_showMessage(
context,
'🎉 Earned reward: ${reward.amount} ${reward.type}',
);
},
onCompleted: () {
_showMessage(context, 'Rewarded flow finished');
},
);
},
),
const SizedBox(height: 12),
// Fullscreen Native Interstitial Dialog Button
OutlinedButton.icon(
icon: const Icon(Icons.picture_in_picture_alt),
label: const Text(
'Show Native Dialog (Fullscreen Card)',
),
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 14),
),
onPressed: () {
showNativeAdInterstitialDialog(
context: context,
adKey: 'native_interstitial_dialog',
screenName: 'scrInterstitialDialog',
onAdClosed: () {
_showMessage(
context,
'Native Ad Dialog closed',
);
},
);
},
),
const SizedBox(height: 24),
// Native Ad Showcase Header & Style/Layout Switcher
const Divider(),
const SizedBox(height: 8),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Native Ad Showcase',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
if (_selectedNativeType ==
NativeDemoType.customLayout &&
_isCustomLayoutDismissed)
TextButton.icon(
icon: const Icon(Icons.refresh, size: 16),
label: const Text('Reset Ad'),
onPressed: () {
setState(
() => _isCustomLayoutDismissed = false,
);
},
),
],
),
const SizedBox(height: 12),
// Segmented controller for Presets and Custom Native Ad features
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: SegmentedButton<NativeDemoType>(
segments: const [
ButtonSegment(
value: NativeDemoType.presetMediaView,
label: Text('MediaView'),
icon: Icon(Icons.view_agenda_outlined),
),
ButtonSegment(
value: NativeDemoType.presetCls,
label: Text('CLS'),
icon: Icon(Icons.vertical_split_outlined),
),
ButtonSegment(
value: NativeDemoType.customStyle,
label: Text('Custom Style'),
icon: Icon(Icons.palette_outlined),
),
ButtonSegment(
value: NativeDemoType.customLayout,
label: Text('Custom Layout'),
icon: Icon(Icons.dashboard_customize_outlined),
),
],
selected: {_selectedNativeType},
onSelectionChanged: (newSelection) {
setState(() {
_selectedNativeType = newSelection.first;
_isCustomLayoutDismissed = false;
});
},
),
),
const SizedBox(height: 12),
// Render selected Native Ad Mode (height: null auto-resizes to native view height without reloading)
if (_adWidgetsSuspended)
const SizedBox(height: 120)
else if (_selectedNativeType ==
NativeDemoType.presetMediaView)
NativeAdWidget(
key: const ValueKey('home_showcase_native'),
adKey: 'home_feed_native',
screenName: 'scrHome',
adPlacement: 'scrHome',
templatePreset: NativeTemplatePreset.mediaView,
margin: const EdgeInsets.symmetric(vertical: 8.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10.0),
boxShadow: const [
BoxShadow(
color: Color(0x0F000000),
blurRadius: 8.0,
offset: Offset(0, 2),
),
],
),
onAdLoaded: (_) {
_showMessage(
context,
'MediaView Native Ad loaded successfully',
);
},
)
else if (_selectedNativeType ==
NativeDemoType.presetCls)
NativeAdWidget(
key: const ValueKey('home_showcase_native'),
adKey: 'home_cls_native',
screenName: 'scrHome',
adPlacement: 'scrHome',
templatePreset: NativeTemplatePreset.cls,
margin: const EdgeInsets.symmetric(vertical: 8.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10.0),
boxShadow: const [
BoxShadow(
color: Color(0x0F000000),
blurRadius: 8.0,
offset: Offset(0, 2),
),
],
),
onAdLoaded: (_) {
_showMessage(
context,
'CLS Native Ad loaded successfully',
);
},
)
else if (_selectedNativeType ==
NativeDemoType.customStyle)
NativeAdWidget(
key: const ValueKey('home_showcase_native'),
adKey: 'home_custom_style_native',
screenName: 'scrHome',
adPlacement: 'scrHome',
margin: const EdgeInsets.symmetric(vertical: 8.0),
nativeTemplateStyle: AdmobNativeStyles.custom(
templateType: TemplateType.medium,
ctaColor: const Color(0xFF6200EE),
ctaTextColor: Colors.white,
backgroundColor: Colors.white,
titleColor: const Color(0xFF1E1E1E),
bodyColor: const Color(0xFF666666),
badgeColor: const Color(0xFF6200EE),
badgeBackgroundColor: const Color(0xFFEDE7F6),
cornerRadius: 16.0,
titleFontSize: 15.0,
bodyFontSize: 12.0,
ctaFontSize: 14.0,
),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16.0),
border: Border.all(
color: const Color(0xFFD1C4E9),
width: 1.5,
),
boxShadow: const [
BoxShadow(
color: Color(0x1A6200EE),
blurRadius: 12.0,
offset: Offset(0, 4),
),
],
),
onAdLoaded: (_) {
_showMessage(
context,
'Custom Style Native Ad loaded successfully',
);
},
)
else if (_selectedNativeType ==
NativeDemoType.customLayout)
_isCustomLayoutDismissed
? Container(
padding: const EdgeInsets.all(24.0),
margin: const EdgeInsets.symmetric(
vertical: 8.0,
),
decoration: BoxDecoration(
color: Colors.grey.shade100,
borderRadius: BorderRadius.circular(10.0),
border: Border.all(
color: Colors.grey.shade300,
),
),
child: Column(
children: [
const Icon(
Icons.visibility_off,
size: 36,
color: Colors.grey,
),
const SizedBox(height: 8),
const Text(
'Ad dismissed (onClose)',
style: TextStyle(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 8),
ElevatedButton.icon(
icon: const Icon(
Icons.refresh,
size: 16,
),
label: const Text('Show Ad Again'),
onPressed: () {
setState(
() => _isCustomLayoutDismissed =
false,
);
},
),
],
),
)
: NativeAdWidget(
key: const ValueKey('home_showcase_native'),
adKey: 'home_custom_layout_native',
screenName: 'scrHome',
adPlacement: 'scrHome',
templatePreset: NativeTemplatePreset.cls,
margin: const EdgeInsets.symmetric(
vertical: 8.0,
),
showCloseButton: true,
closeButtonAlignment: Alignment.topRight,
onClose: () {
_showMessage(
context,
'Custom Native Ad closed by user',
);
setState(
() => _isCustomLayoutDismissed = true,
);
},
header: Container(
padding: const EdgeInsets.symmetric(
horizontal: 12.0,
vertical: 8.0,
),
decoration: const BoxDecoration(
color: Color(0xFFE8F5E9),
borderRadius: BorderRadius.vertical(
top: Radius.circular(10.0),
),
),
child: const Row(
children: [
Icon(
Icons.stars_rounded,
size: 18,
color: Colors.green,
),
SizedBox(width: 8),
Text(
'Recommended Content (Custom Header)',
style: TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
fontSize: 13,
),
),
],
),
),
footer: Container(
padding: const EdgeInsets.symmetric(
vertical: 8.0,
),
alignment: Alignment.center,
decoration: const BoxDecoration(
color: Color(0xFFFAFAFA),
borderRadius: BorderRadius.vertical(
bottom: Radius.circular(10.0),
),
),
child: const Text(
'Google AdMob • Tap to learn more (Custom Footer)',
style: TextStyle(
fontSize: 11,
color: Colors.grey,
),
),
),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10.0),
border: Border.all(
color: Colors.green.shade200,
),
boxShadow: const [
BoxShadow(
color: Color(0x0F000000),
blurRadius: 8.0,
offset: Offset(0, 2),
),
],
),
onAdLoaded: (_) {
_showMessage(
context,
'Custom Layout Native Ad loaded successfully',
);
},
),
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
_selectedNativeType ==
NativeDemoType.presetMediaView
? '• Preset MediaView: Google AdMob standard centered media template.'
: _selectedNativeType ==
NativeDemoType.presetCls
? '• Preset CLS: Layout optimized to prevent Cumulative Layout Shift.'
: _selectedNativeType ==
NativeDemoType.customStyle
? '• Custom Style: AdmobNativeStyles.custom() with brand purple, 16px radius, custom typography.'
: '• Custom Layout: Custom green Header, Footer, close button (X), and onClose handler.',
style: const TextStyle(
fontSize: 12,
color: Colors.grey,
),
textAlign: TextAlign.center,
),
),
],
),
),
),
// Banner optimization switcher
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'Standard Banner',
style: TextStyle(fontSize: 12),
),
Switch(
value: _useCollapsibleAdaptiveBanner,
onChanged: (val) {
setState(() => _useCollapsibleAdaptiveBanner = val);
},
),
const Text(
'Collapsible Adaptive (High eCPM)',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
),
),
],
),
),
// Pre-built BannerAdWidget with adKey and screenName
SafeArea(
child: Container(
alignment: Alignment.center,
child: _adWidgetsSuspended
? const SizedBox(height: 50)
: _useCollapsibleAdaptiveBanner
? BannerAdWidget.adaptive(
key: const ValueKey('adaptive_collapsible_banner'),
adKey: 'home_bottom_collapsible_banner',
screenName: 'scrHome',
adPlacement: 'scrHome',
collapsiblePlacement: CollapsiblePlacement.bottom,
)
: const BannerAdWidget(
key: ValueKey('standard_banner'),
adKey: 'home_bottom_banner',
screenName: 'scrHome',
adPlacement: 'scrHome',
adSize: AdSize.banner,
),
),
),
],
);
},
),
),
);
}
}