admob_ads_manager 1.0.1
admob_ads_manager: ^1.0.1 copied to clipboard
A simplified Flutter package for AdMob ads integration with support for Banner, Native, Interstitial, Rewarded, and AppOpen ads.
AdMob Ads Manager #
A simplified Flutter package for AdMob ads integration with support for Banner, Native, Interstitial, Rewarded, and AppOpen ads. Built on top of google_mobile_ads: ^7.0.0 with full support for AdMob mediation.
Features #
- ๐ฏ Easy Integration: One-line integration for each ad type
- ๐ Auto Preloading: Automatic ad preloading and reloading after display
- ๐งช Test Mode: Full support for test and production modes
- ๐ฑ All Ad Types: Banner, Native, Interstitial, Rewarded, and AppOpen ads
- ๐จ Customizable: Flexible design options for banner and native ads
- ๐ Smart Management: Prevents overlapping ads (especially with AppOpen)
- ๐ AdMob Mediation: Full support for AdMob mediation with multiple ad networks
- ๐ Debug Logging: Optional logging for debugging ad events
- ๐ Cross-Platform: Works seamlessly on Android and iOS
Installation #
Add this to your package's pubspec.yaml file:
dependencies:
admob_ads_manager: ^1.0.1
Then run:
flutter pub get
Important: You must configure AdMob App IDs in your Android and iOS projects. See the Setup Guide for detailed instructions.
Platform Setup #
Android #
Add your AdMob App ID to android/app/src/main/AndroidManifest.xml:
<manifest>
<application>
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>
</application>
</manifest>
iOS #
Add your AdMob App ID to ios/Runner/Info.plist:
<key>GADApplicationIdentifier</key>
<string>ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy</string>
Complete Example #
Check out the example directory for a complete working Flutter app demonstrating all ad types.
To run the example:
cd example
flutter pub get
flutter run
The example includes proper Android/iOS configuration and demonstrates all 5 ad types.
Usage #
1. Initialization #
Initialize the package before displaying any ads (typically in main.dart):
import 'package:admob_ads_manager/admob_ads_manager.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await AdsManager.init(
adIds: AdIds(
androidBanner: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
iosBanner: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
androidInterstitial: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
iosInterstitial: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
androidRewarded: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
iosRewarded: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
androidNative: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
iosNative: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
androidAppOpen: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
iosAppOpen: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
),
isTestMode: true, // Set to false for production
enableLogging: true, // Optional: Enable debug logging
);
runApp(MyApp());
}
Simplified Option: If you only need specific ad types, you can omit the others:
await AdsManager.init(
adIds: AdIds(
androidBanner: "ca-app-pub-xxx",
iosBanner: "ca-app-pub-yyy",
androidInterstitial: "ca-app-pub-xxx",
iosInterstitial: "ca-app-pub-yyy",
// Only include the ad types you need
),
isTestMode: true,
);
Cross-Platform Option: If your ad IDs are the same for both platforms (rare but possible):
await AdsManager.init(
adIds: AdIds.crossPlatform(
banner: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
interstitial: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
rewarded: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
),
isTestMode: true,
);
2. Banner Ads #
Display banner ads anywhere in your widget tree:
BannerAdWidget(
adSize: AdSize.banner, // or AdSize.largeBanner, AdSize.mediumRectangle
onError: (error) {
print("Banner failed to load: $error");
},
padding: EdgeInsets.all(8.0),
alignment: Alignment.bottomCenter,
backgroundColor: Colors.grey[200],
)
3. Native Ads #
Display customizable native ads:
NativeAdWidget(
width: 300,
height: 250,
style: NativeAdStyle.card, // card, minimal, or full
onLoad: () {
print("Native ad loaded successfully");
},
onError: (error) {
print("Native ad failed: $error");
},
backgroundColor: Colors.white,
headlineTextStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.black,
),
bodyTextStyle: TextStyle(
fontSize: 14,
color: Colors.grey[700],
),
callToActionTextStyle: TextStyle(
fontSize: 14,
color: Colors.white,
),
callToActionBackgroundColor: Colors.blue,
padding: EdgeInsets.all(8.0),
)
4. Interstitial Ads #
Show full-screen interstitial ads:
await AdsManager.showInterstitial(
onLoad: () => print("Interstitial loaded"),
onError: (error) => print("Interstitial failed: $error"),
onDismiss: () => print("Interstitial dismissed"),
);
5. Rewarded Ads #
Show rewarded ads and handle user rewards:
await AdsManager.showRewarded(
onLoad: () => print("Rewarded ad loaded"),
onError: (error) => print("Rewarded ad failed: $error"),
onEarnReward: (reward) {
print("User earned: ${reward.amount} ${reward.type}");
// Grant reward to user
},
onDismiss: () => print("Rewarded ad dismissed"),
);
6. AppOpen Ads #
Show app open ads when your app starts or comes to foreground:
Manual AppOpen Ads
await AdsManager.showAppOpen(
onLoad: () => print("AppOpen ad loaded"),
onError: (error) => print("AppOpen failed: $error"),
onDismiss: () => print("AppOpen dismissed"),
);
Automatic AppOpen Ads (NEW in v1.0.1)
Enable automatic AppOpen ads that show when your app comes to foreground:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await AdsManager.init(
adIds: AdIds(...),
isTestMode: true,
);
// Enable auto AppOpen ads
// minIntervalSeconds: 0 = show on every app resume (default)
// Set higher value to limit frequency (e.g., 3600 for 1 hour)
AdsManager.enableAutoAppOpen(minIntervalSeconds: 0);
runApp(MyApp());
}
Control auto AppOpen ads at runtime:
// Enable auto AppOpen ads
AdsManager.enableAutoAppOpen(minIntervalSeconds: 3600); // Show max once per hour
// Disable auto AppOpen ads
AdsManager.disableAutoAppOpen();
// Check if auto AppOpen is enabled
bool isEnabled = AdsManager.isAutoAppOpenEnabled;
How it works:
- Automatically shows AppOpen ad when app comes to foreground (from background)
- Respects minimum interval between ads (prevents showing too frequently)
- Won't show if another ad is already displaying
- Automatically reloads ads after they're shown
Note: AppOpen ads prevent other ads from showing while active to avoid overlap.
Complete Example #
import 'package:flutter/material.dart';
import 'package:admob_ads_manager/admob_ads_manager.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await AdsManager.init(
adIds: AdIds(
androidBanner: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
iosBanner: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
androidInterstitial: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
iosInterstitial: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
androidRewarded: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
iosRewarded: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
androidNative: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
iosNative: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
androidAppOpen: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
iosAppOpen: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
),
isTestMode: true,
enableLogging: true,
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('AdMob Ads Manager Demo')),
body: Column(
children: [
Expanded(
child: ListView(
padding: EdgeInsets.all(16),
children: [
ElevatedButton(
onPressed: () async {
await AdsManager.showInterstitial(
onDismiss: () => print('Interstitial dismissed'),
);
},
child: Text('Show Interstitial Ad'),
),
SizedBox(height: 16),
ElevatedButton(
onPressed: () async {
await AdsManager.showRewarded(
onEarnReward: (reward) {
print('Earned ${reward.amount} ${reward.type}');
},
);
},
child: Text('Show Rewarded Ad'),
),
SizedBox(height: 16),
ElevatedButton(
onPressed: () async {
await AdsManager.showAppOpen(
onDismiss: () => print('AppOpen dismissed'),
);
},
child: Text('Show AppOpen Ad'),
),
SizedBox(height: 16),
NativeAdWidget(
height: 250,
style: NativeAdStyle.card,
),
],
),
),
BannerAdWidget(
adSize: AdSize.banner,
alignment: Alignment.bottomCenter,
),
],
),
);
}
}
API Reference #
AdsManager #
Methods
init()- Initialize the ads managershowInterstitial()- Show an interstitial adshowRewarded()- Show a rewarded adshowAppOpen()- Show an app open addispose()- Dispose all ads
Properties
isInitialized- Check if manager is initializedisAppOpenAdShowing- Check if app open ad is currently showing
BannerAdWidget #
Parameters
adSize- Ad size (default:AdSize.banner)onError- Error callbackpadding- Widget paddingalignment- Widget alignmentbackgroundColor- Background color
NativeAdWidget #
Parameters
width- Ad widthheight- Ad heightstyle- Ad style (card,minimal,full)onLoad- Load success callbackonError- Error callbackbackgroundColor- Background colorheadlineTextStyle- Headline text stylebodyTextStyle- Body text stylecallToActionTextStyle- CTA text stylecallToActionBackgroundColor- CTA background colorpadding- Widget padding
Best Practices #
- Initialize Early: Call
AdsManager.init()in yourmain()function beforerunApp() - Test Mode: Always use
isTestMode: trueduring development to avoid policy violations - Error Handling: Implement error callbacks to handle ad loading failures gracefully
- User Experience: Show interstitial ads at natural breaks in your app (level completion, navigation)
- Rewards: Always grant rewards in the
onEarnRewardcallback for rewarded ads - AppOpen Ads: Use sparingly (app launch only) to avoid annoying users
- Auto AppOpen: Set appropriate
minIntervalSecondsto prevent showing ads too frequently - Dispose: The package automatically handles ad disposal and reloading
Auto AppOpen Ads Feature #
The auto AppOpen ads feature automatically shows AppOpen ads when your app comes to foreground from background. This is perfect for monetizing app resumes without manual implementation.
Setup #
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await AdsManager.init(
adIds: AdIds(...),
isTestMode: true,
);
// Enable auto AppOpen ads
AdsManager.enableAutoAppOpen(
minIntervalSeconds: 3600, // Show max once per hour
);
runApp(MyApp());
}
Configuration Options #
// Show on every app resume (not recommended for production)
AdsManager.enableAutoAppOpen(minIntervalSeconds: 0);
### Runtime Control
```dart
// Disable auto AppOpen ads
AdsManager.disableAutoAppOpen();
// Check current status
if (AdsManager.isAutoAppOpenEnabled) {
print('Auto AppOpen is active');
}
How It Works #
- App Lifecycle Monitoring: Listens to app lifecycle changes
- Foreground Detection: Detects when app comes from background to foreground
- Interval Check: Ensures minimum time has passed since last ad
- Automatic Display: Shows AppOpen ad automatically
- Auto Reload: Preloads next ad after current one is dismissed
Best Practices for Auto AppOpen #
- Set Reasonable Intervals: Don't show ads too frequently (recommended: 1-4 hours)
- Test User Experience: Ensure ads don't annoy users
- Monitor Metrics: Check AdMob dashboard for user retention impact
- Combine with Manual: Use auto for background-to-foreground, manual for app launch
- Respect User Actions: Don't show if user is in middle of important action
Example: Complete Implementation #
import 'package:flutter/material.dart';
import 'package:admob_ads_manager/admob_ads_manager.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await AdsManager.init(
adIds: AdIds(
androidAppOpen: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
iosAppOpen: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
// ... other ad types
),
isTestMode: false, // Production mode
enableLogging: false,
);
// Enable auto AppOpen with 1 hour interval
AdsManager.enableAutoAppOpen(minIntervalSeconds: 3600);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My App'),
actions: [
// Toggle auto AppOpen ads
IconButton(
icon: Icon(
AdsManager.isAutoAppOpenEnabled
? Icons.ads_click
: Icons.block,
),
onPressed: () {
if (AdsManager.isAutoAppOpenEnabled) {
AdsManager.disableAutoAppOpen();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Auto ads disabled')),
);
} else {
AdsManager.enableAutoAppOpen(minIntervalSeconds: 3600);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Auto ads enabled')),
);
}
},
),
],
),
body: Center(
child: Text('Put app in background and bring back to see auto AppOpen ad'),
),
);
}
}
Testing Auto AppOpen Ads #
- Enable Test Mode: Use
isTestMode: trueduring development - Set Short Interval: Use
minIntervalSeconds: 0or whatever delay you want to add - Test Flow:
- Launch app
- Put app in background (home button)
- Wait a few seconds
- Bring app to foreground
- AppOpen ad should show automatically
- Check Logs: Enable logging to see lifecycle events
- Verify Interval: Test with different interval values
AdMob Mediation Setup #
AdMob mediation allows you to show ads from multiple ad networks to maximize your revenue. This package fully supports AdMob mediation through the underlying google_mobile_ads package.
What is AdMob Mediation? #
AdMob mediation enables you to:
- Show ads from multiple ad networks (Facebook, Unity, AppLovin, etc.)
- Automatically optimize which network to use for each ad request
- Increase fill rates and eCPM
- Manage all networks from the AdMob dashboard
How to Enable Mediation #
Step 1: Set Up Mediation in AdMob Console
- Go to AdMob Console
- Navigate to Mediation โ Mediation Groups
- Click Create Mediation Group
- Select your ad format (Banner, Interstitial, Rewarded, Native)
- Add ad sources (networks) you want to mediate
- Configure waterfall or bidding settings
- Link your ad units to the mediation group
Step 2: Add Network Adapters to Your App
For each ad network you want to mediate, add the corresponding adapter dependency.
Android Setup
Add to android/app/build.gradle inside dependencies block:
dependencies {
// Facebook Audience Network
implementation 'com.google.ads.mediation:facebook:6.17.0.0'
// Unity Ads
implementation 'com.google.ads.mediation:unity:4.12.2.0'
// AppLovin
implementation 'com.google.ads.mediation:applovin:12.6.0.0'
// Vungle
implementation 'com.google.ads.mediation:vungle:7.4.0.0'
// AdColony
implementation 'com.google.ads.mediation:adcolony:4.8.0.3'
// Chartboost
implementation 'com.google.ads.mediation:chartboost:9.7.0.0'
// InMobi
implementation 'com.google.ads.mediation:inmobi:10.7.5.0'
// IronSource
implementation 'com.google.ads.mediation:ironsource:8.3.0.0'
// Pangle (TikTok)
implementation 'com.google.ads.mediation:pangle:6.1.0.9.0'
// Mintegral
implementation 'com.google.ads.mediation:mintegral:16.7.71.0'
}
Note: Check Google's official adapter versions for the latest versions.
iOS Setup
Add to ios/Podfile:
target 'Runner' do
use_frameworks!
use_modular_headers!
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
# Facebook Audience Network
pod 'GoogleMobileAdsMediationFacebook'
# Unity Ads
pod 'GoogleMobileAdsMediationUnity'
# AppLovin
pod 'GoogleMobileAdsMediationAppLovin'
# Vungle
pod 'GoogleMobileAdsMediationVungle'
# AdColony
pod 'GoogleMobileAdsMediationAdColony'
# Chartboost
pod 'GoogleMobileAdsMediationChartboost'
# InMobi
pod 'GoogleMobileAdsMediationInMobi'
# IronSource
pod 'GoogleMobileAdsMediationIronSource'
# Pangle (TikTok)
pod 'GoogleMobileAdsMediationPangle'
# Mintegral
pod 'GoogleMobileAdsMediationMintegral'
end
Then run:
cd ios
pod install --repo-update
cd ..
Step 3: Configure Network-Specific Settings
Some networks require additional configuration:
Facebook Audience Network
Android - Add to AndroidManifest.xml:
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="fb-app-id://YOUR_FACEBOOK_APP_ID"/>
iOS - Add to Info.plist:
<key>FacebookAppID</key>
<string>YOUR_FACEBOOK_APP_ID</string>
<key>FacebookDisplayName</key>
<string>YOUR_APP_NAME</string>
AppLovin
Android - Add to AndroidManifest.xml:
<meta-data
android:name="applovin.sdk.key"
android:value="YOUR_APPLOVIN_SDK_KEY"/>
iOS - Add to Info.plist:
<key>AppLovinSdkKey</key>
<string>YOUR_APPLOVIN_SDK_KEY</string>
Unity Ads
Android - Add to AndroidManifest.xml:
<meta-data
android:name="com.google.android.gms.ads.UNITY_GAME_ID"
android:value="YOUR_UNITY_GAME_ID"/>
iOS - Add to Info.plist:
<key>UnityAdsGameId</key>
<string>YOUR_UNITY_GAME_ID</string>
Step 4: Use Your Mediation Ad Units
Important: When using mediation, use your AdMob ad unit IDs (not the network-specific IDs). AdMob handles the mediation automatically.
await AdsManager.init(
adIds: AdIds(
// Use your AdMob ad unit IDs (same as before)
androidBanner: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
iosBanner: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
androidInterstitial: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
iosInterstitial: "ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxx",
// ... other ad types
),
isTestMode: false, // Use false for production
enableLogging: true, // Enable to see which network serves ads
);
Popular Mediation Networks #
| Network | Best For | Minimum SDK |
|---|---|---|
| Facebook Audience Network | High eCPM, global reach | Android 21+, iOS 12+ |
| Unity Ads | Gaming apps, video ads | Android 21+, iOS 12+ |
| AppLovin | High fill rates, MAX platform | Android 21+, iOS 12+ |
| Vungle | Video ads, gaming | Android 21+, iOS 12+ |
| IronSource | Gaming, rewarded videos | Android 21+, iOS 12+ |
| AdColony | Video ads, high quality | Android 21+, iOS 12+ |
| Pangle (TikTok) | Asian markets, video ads | Android 21+, iOS 12+ |
| InMobi | Emerging markets | Android 21+, iOS 12+ |
Testing Mediation #
- Enable Test Mode: Use
isTestMode: trueduring development - Check Logs: Enable logging to see which network serves each ad:
await AdsManager.init( adIds: AdIds(...), isTestMode: true, enableLogging: true, // See ad network logs ); - Test Each Network: In AdMob console, you can force specific networks for testing
- Monitor Performance: Use AdMob dashboard to track which networks perform best
Mediation Best Practices #
- Start with 3-5 Networks: Don't add too many networks initially
- Monitor eCPM: Regularly check which networks provide the best revenue
- Update Adapters: Keep adapter versions up to date for best performance
- Test Thoroughly: Test on real devices before releasing
- Respect Privacy: Ensure all networks comply with GDPR/CCPA requirements
- Optimize Waterfall: Adjust network priorities based on performance data
- Use Bidding: Enable bidding for supported networks to maximize revenue
Troubleshooting Mediation #
Problem: Mediation ads not showing
Solutions:
- Verify adapter dependencies are added correctly
- Check that mediation group is properly configured in AdMob console
- Ensure network-specific configurations (API keys) are correct
- Run
flutter clean && flutter pub get(andpod installfor iOS) - Check console logs for network-specific errors
- Verify your app is approved by each ad network
Problem: Only AdMob ads showing, not mediated networks
Solutions:
- Confirm mediation group is linked to your ad units
- Check that adapters are properly installed
- Verify network accounts are active and approved
- Test with
isTestMode: truefirst - Allow 24-48 hours for new mediation setup to propagate
Resources #
License #
This project is licensed under the MIT License - see the LICENSE file for details.