google_admob_sdk 1.0.2
google_admob_sdk: ^1.0.2 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';
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 ID configurations and Firebase / Console loggers
await GoogleAdmobSdk.initialize(
config: const AdIdConfig(
android: PlatformAdIds(
bannerId: 'ca-app-pub-3940256099942544/6300978111',
interstitialId: 'ca-app-pub-3940256099942544/1033173712',
rewardedId: 'ca-app-pub-3940256099942544/5224354917',
appOpenId: 'ca-app-pub-3940256099942544/9257395921',
nativeId: 'ca-app-pub-3940256099942544/2247696110',
),
ios: PlatformAdIds(
bannerId: 'ca-app-pub-3940256099942544/2934735716',
interstitialId: 'ca-app-pub-3940256099942544/4411468910',
rewardedId: 'ca-app-pub-3940256099942544/1712485313',
appOpenId: 'ca-app-pub-3940256099942544/5608718254',
nativeId: 'ca-app-pub-3940256099942544/3986624511',
),
),
logger: FirebaseAdLogger(),
enableLogging: true,
enableDeviceLog: true,
maxAdContentRating: MaxAdContentRating.g,
ageRestrictedTreatment: TagForChildDirectedTreatment.no,
);
runApp(const MyApp());
}
/// Demo modes for showcasing Native Ad capabilities
enum NativeDemoType {
presetMediaView,
presetCls,
customStyle,
customLayout,
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late final AppLifecycleReactor _lifecycleReactor;
NativeDemoType _selectedNativeType = NativeDemoType.presetMediaView;
bool _isCustomLayoutDismissed = false;
bool _useCollapsibleAdaptiveBanner = true;
@override
void initState() {
super.initState();
// 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',
);
// 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();
}
@override
void dispose() {
_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: 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 (_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: _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,
),
),
),
],
);
},
),
),
);
}
}