google_admob_sdk 0.0.7
google_admob_sdk: ^0.0.7 copied to clipboard
A Flutter plugin for Google Mobile Ads (AdMob) with centralized Ad Unit ID management, load duration metrics, adKey tracking, and pre-built ad widgets & managers.
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,
);
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> {
final _interstitialManager = InterstitialAdManager();
final _rewardedManager = RewardedAdManager();
final _appOpenManager = AppOpenAdManager();
NativeDemoType _selectedNativeType = NativeDemoType.presetMediaView;
bool _isCustomLayoutDismissed = false;
@override
void initState() {
super.initState();
// Preload ads with custom placement keys (adKey) and screenName for logging
_interstitialManager.loadAd(
adKey: 'level_complete_interstitial',
screenName: 'scrLevelComplete',
adPlacement: 'scrLevelComplete',
);
_rewardedManager.loadAd(
adKey: 'extra_lives_rewarded',
screenName: 'scrShop',
adPlacement: 'scrShop',
);
_appOpenManager.loadAd(
adKey: 'app_launch_open_ad',
screenName: 'scrSplash',
adPlacement: 'scrSplash',
);
}
@override
void dispose() {
_interstitialManager.dispose();
_rewardedManager.dispose();
_appOpenManager.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, Rewarded, App Open, and Native ads (Presets, Custom Styles & Layouts) 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 (_appOpenManager.isAdAvailable) {
await _appOpenManager.showAdIfAvailable(
adKey: 'app_launch_open_ad',
);
} else {
_showMessage(
context,
'App Open Ad is loading...',
);
_appOpenManager.loadAd(
adKey: 'app_launch_open_ad',
);
}
},
),
const SizedBox(height: 12),
// Interstitial Ad Button
ElevatedButton.icon(
icon: const Icon(Icons.fullscreen),
label: const Text('Show Interstitial Ad'),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 14),
),
onPressed: () async {
if (_interstitialManager.isAdLoaded) {
await _interstitialManager.showAd(
adKey: 'level_complete_interstitial',
onAdDismissedFullScreenContent: () {
_showMessage(
context,
'Interstitial Ad dismissed',
);
},
);
} else {
_showMessage(
context,
'Interstitial Ad is loading...',
);
_interstitialManager.loadAd(
adKey: 'level_complete_interstitial',
);
}
},
),
const SizedBox(height: 12),
// Rewarded Ad Button
ElevatedButton.icon(
icon: const Icon(Icons.card_giftcard),
label: const Text('Show Rewarded Ad'),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 14),
),
onPressed: () async {
if (_rewardedManager.isAdLoaded) {
await _rewardedManager.showAd(
adKey: 'extra_lives_rewarded',
onUserEarnedReward: (ad, reward) {
_showMessage(
context,
'🎉 Earned reward: ${reward.amount} ${reward.type}',
);
},
);
} else {
_showMessage(
context,
'Rewarded Ad is loading...',
);
_rewardedManager.loadAd(
adKey: 'extra_lives_rewarded',
);
}
},
),
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
if (_selectedNativeType == NativeDemoType.presetMediaView)
NativeAdWidget(
key: const ValueKey('preset_media_view'),
adKey: 'home_feed_native',
screenName: 'scrHome',
adPlacement: 'scrHome',
templatePreset: NativeTemplatePreset.mediaView,
height: 320.0,
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('preset_cls'),
adKey: 'home_cls_native',
screenName: 'scrHome',
adPlacement: 'scrHome',
templatePreset: NativeTemplatePreset.cls,
height: 320.0,
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('custom_style'),
adKey: 'home_custom_style_native',
screenName: 'scrHome',
adPlacement: 'scrHome',
height: 320.0,
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(
'Quảng cáo đã được đóng (onClose)',
style: TextStyle(fontWeight: FontWeight.w600),
),
const SizedBox(height: 8),
ElevatedButton.icon(
icon: const Icon(Icons.refresh, size: 16),
label: const Text('Hiện lại Ad'),
onPressed: () {
setState(() => _isCustomLayoutDismissed = false);
},
),
],
),
)
: NativeAdWidget(
key: const ValueKey('custom_layout'),
adKey: 'home_custom_layout_native',
screenName: 'scrHome',
adPlacement: 'scrHome',
templatePreset: NativeTemplatePreset.cls,
height: 360.0,
margin: const EdgeInsets.symmetric(vertical: 8.0),
showCloseButton: true,
closeButtonAlignment: Alignment.topRight,
onClose: () {
_showMessage(context, 'Custom Native Ad đóng bởi người dùng');
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(
'Nội dung được đề xuất (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(
'Quảng cáo Google AdMob • Chạm để tìm hiểu thêm (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: Mẫu quảng cáo trung tâm chuẩn Google AdMob.'
: _selectedNativeType == NativeDemoType.presetCls
? '• Preset CLS: Mẫu tối ưu ngăn ngừa Cumulative Layout Shift.'
: _selectedNativeType == NativeDemoType.customStyle
? '• Custom Style: AdmobNativeStyles.custom() tùy biến màu tím thương hiệu, bo góc 16px, font chữ tùy chỉnh.'
: '• Custom Layout: Tùy biến Header xanh lá, Footer, nút đóng (X) và xử lý sự kiện onClose.',
style: const TextStyle(fontSize: 12, color: Colors.grey),
textAlign: TextAlign.center,
),
),
],
),
),
),
// Pre-built BannerAdWidget with adKey and screenName
SafeArea(
child: Container(
alignment: Alignment.center,
child: const BannerAdWidget(
adKey: 'home_bottom_banner',
screenName: 'scrHome',
adPlacement: 'scrHome',
adSize: AdSize.banner,
),
),
),
],
);
},
),
),
);
}
}