### Initialize AppLovin SDK Early Source: https://developers.google.com/admob/flutter/mediation/applovin Call `GmaMediationApplovin.initializeSdk('sdkKey')` in your launch activity to enable AppLovin to track events as soon as the app starts. ```dart GmaMediationApplovin.initializeSdk('sdkKey') ``` -------------------------------- ### Initialize Ads and App Lifecycle Reactor Source: https://developers.google.com/admob/flutter/app-open Initializes the Google Mobile Ads SDK and sets up the AppLifecycleReactor to manage app open ads based on app state changes. This is typically done at the start of the application. ```dart import 'package:app_open_example/app_open_ad_manager.dart'; import 'package:flutter/material.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart'; import 'app_lifecycle_reactor.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); MobileAds.instance.initialize(); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'App Open Example', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'App Open Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } /// Example home page for an app open ad. class _MyHomePageState extends State { int _counter = 0; late AppLifecycleReactor _appLifecycleReactor; @override void initState() { super.initState(); AppOpenAdManager appOpenAdManager = AppOpenAdManager()..loadAd(); _appLifecycleReactor = AppLifecycleReactor( appOpenAdManager: appOpenAdManager); } ``` -------------------------------- ### Displaying Native Ads with AdWidget (Small Template) Source: https://developers.google.com/admob/flutter/native/templates Use AdWidget to display a loaded NativeAd. Ensure the widget is placed within a container with specified dimensions, especially on iOS. This example uses the small template. ```dart // Small template final adContainer = ConstrainedBox( constraints: const BoxConstraints( minWidth: 320, // minimum recommended width minHeight: 90, // minimum recommended height maxWidth: 400, maxHeight: 200, ), child: AdWidget(ad: _nativeAd!), ); ``` -------------------------------- ### Android MainActivity Setup for AppLovin Privacy APIs Source: https://developers.google.com/admob/flutter/mediation/network-apis Configure the MainActivity in Android to set up a method channel that handles calls for AppLovin privacy settings. It maps incoming method calls to the corresponding AppLovin SDK functions. ```java public class MainActivity extends FlutterActivity { private static final String CHANNEL_NAME = "com.example.mediationexample/mediation-channel"; @Override public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { super.configureFlutterEngine(flutterEngine); // Set up a method channel for calling APIs in the AppLovin SDK. new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL) .setMethodCallHandler( (call, result) -> { switch (call.method) { case "setIsAgeRestrictedUser": AppLovinPrivacySettings.setIsAgeRestrictedUser(call.argument("isAgeRestricted"), context); result.success(null); break; case "setHasUserConsent": AppLovinPrivacySettings.setHasUserConsent(call.argument("hasUserConsent"), context); result.success(null); break; default: result.notImplemented(); break; } } ); } } ``` -------------------------------- ### Implement MediationNetworkExtrasProvider on Android Source: https://developers.google.com/admob/flutter/mediation/network-specific-parameters Implement the `MediationNetworkExtrasProvider` interface to define custom network extras. This example shows how to pass extras to the AppLovin adapter, setting the audio to mute. ```java class MyMediationNetworkExtrasProvider implements MediationNetworkExtrasProvider { @Override public Map, Bundle> getMediationExtras( String adUnitId, @Nullable String identifier) { // This example passes extras to the AppLovin adapter. // This method is called with the ad unit of the associated ad request, and // an optional string parameter which comes from the dart ad request object. Bundle appLovinBundle = new AppLovinExtras.Builder().setMuteAudio(true).build(); Map, Bundle> extras = new HashMap<>(); extras.put(ApplovinAdapter.class, appLovinBundle); // Note: You can pass extras to multiple adapters by adding more entries. return extras; } } ``` -------------------------------- ### Inline Adaptive Banner Example Widget Source: https://developers.google.com/admob/flutter/banner/inline-adaptive This Flutter widget demonstrates loading and displaying an inline adaptive banner ad. It handles ad loading, size adaptation for different orientations, and reloads the ad when the device orientation changes. Use this for ads that need to fit within a scrolling content area. ```dart import 'package:flutter/material.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart'; /// This example demonstrates inline adaptive banner ads. /// /// Loads and shows an inline adaptive banner ad in a scrolling view, /// and reloads the ad when the orientation changes. class InlineAdaptiveExample extends StatefulWidget { @override _InlineAdaptiveExampleState createState() => _InlineAdaptiveExampleState(); } class _InlineAdaptiveExampleState extends State { static const _insets = 16.0; BannerAd? _inlineAdaptiveAd; bool _isLoaded = false; AdSize? _adSize; late Orientation _currentOrientation; double get _adWidth => MediaQuery.of(context).size.width - (2 * _insets); @override void didChangeDependencies() { super.didChangeDependencies(); _currentOrientation = MediaQuery.of(context).orientation; _loadAd(); } void _loadAd() async { await _inlineAdaptiveAd?.dispose(); setState(() { _inlineAdaptiveAd = null; _isLoaded = false; }); // Get an inline adaptive size for the current orientation. AdSize size = AdSize.getCurrentOrientationInlineAdaptiveBannerAdSize( _adWidth.truncate()); _inlineAdaptiveAd = BannerAd( // TODO: replace this test ad unit with your own ad unit. adUnitId: 'ca-app-pub-3940256099942544/9214589741', size: size, request: AdRequest(), listener: BannerAdListener( onAdLoaded: (Ad ad) async { print('Inline adaptive banner loaded: ${ad.responseInfo}'); // After the ad is loaded, get the platform ad size and use it to // update the height of the container. This is necessary because the // height can change after the ad is loaded. BannerAd bannerAd = (ad as BannerAd); final AdSize? size = await bannerAd.getPlatformAdSize(); if (size == null) { print('Error: getPlatformAdSize() returned null for $bannerAd'); return; } setState(() { _inlineAdaptiveAd = bannerAd; _isLoaded = true; _adSize = size; }); }, onAdFailedToLoad: (Ad ad, LoadAdError error) { print('Inline adaptive banner failedToLoad: $error'); ad.dispose(); }, ), ); await _inlineAdaptiveAd!.load(); } /// Gets a widget containing the ad, if one is loaded. /// /// Returns an empty container if no ad is loaded, or the orientation /// has changed. Also loads a new ad if the orientation changes. Widget _getAdWidget() { return OrientationBuilder( builder: (context, orientation) { if (_currentOrientation == orientation && _inlineAdaptiveAd != null && _isLoaded && _adSize != null) { return Align( child: Container( width: _adWidth, height: _adSize!.height.toDouble(), child: AdWidget( ad: _inlineAdaptiveAd!, ), )); } // Reload the ad if the orientation changes. if (_currentOrientation != orientation) { _currentOrientation = orientation; _loadAd(); } return Container(); }, ); } @override Widget build(BuildContext context) => Scaffold( appBar: AppBar( title: Text('Inline adaptive banner example'), ), body: Center( child: Padding( padding: const EdgeInsets.symmetric(horizontal: _insets), child: ListView.separated( itemCount: 20, separatorBuilder: (BuildContext context, int index) { return Container( height: 40, ); }, itemBuilder: (BuildContext context, int index) { if (index == 10) { return _getAdWidget(); } return Text( 'Placeholder text', style: TextStyle(fontSize: 24), ); }, ), ), )); @override void dispose() { super.dispose(); _inlineAdaptiveAd?.dispose(); } } ``` -------------------------------- ### Displaying Native Ads with AdWidget (Medium Template) Source: https://developers.google.com/admob/flutter/native/templates Use AdWidget to display a loaded NativeAd. Ensure the widget is placed within a container with specified dimensions, especially on iOS. This example uses the medium template. ```dart // Medium template final adContainer = ConstrainedBox( constraints: const BoxConstraints( minWidth: 320, // minimum recommended width minHeight: 320, // minimum recommended height maxWidth: 400, maxHeight: 400, ), child: AdWidget(ad: _nativeAd!), ); ``` -------------------------------- ### iOS AppDelegate Setup for AppLovin Privacy APIs Source: https://developers.google.com/admob/flutter/mediation/network-apis Set up the AppDelegate in iOS to establish a method channel for interacting with third-party SDKs, specifically handling calls for AppLovin privacy settings. It maps method calls to the appropriate ALPrivacySettings functions. ```objective-c @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [GeneratedPluginRegistrant registerWithRegistry:self]; // Set up a method channel for calling methods in 3P SDKs. FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController; FlutterMethodChannel* methodChannel = [FlutterMethodChannel methodChannelWithName:@"com.example.mediationexample/mediation-channel" binaryMessenger:controller.binaryMessenger]; [methodChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { if ([call.method isEqualToString:@"setIsAgeRestrictedUser"]) { [ALPrivacySettings setIsAgeRestrictedUser:call.arguments[@"isAgeRestricted"]]; result(nil); } else if ([call.method isEqualToString:@"setHasUserConsent"]) { [ALPrivacySettings setHasUserConsent:call.arguments[@"hasUserConsent"]]; result(nil); } else { result(FlutterMethodNotImplemented); } }]; } @end ``` -------------------------------- ### Load a Collapsible Banner Ad Source: https://developers.google.com/admob/flutter/banner/collapsible This snippet demonstrates how to load a collapsible banner ad with a specified placement (e.g., 'bottom'). Ensure you have completed the banner ads get started guide and define your banner view with the desired collapsed size. ```dart void _loadAd() async { // Replace these test ad units with your own ad units. final String adUnitId = Platform.isAndroid ? 'ca-app-pub-3940256099942544/2014213617' : 'ca-app-pub-3940256099942544/8388050270'; // Get the size before loading the ad. final size = await AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize( MediaQuery.sizeOf(context).width.truncate()); if (size == null) { // Unable to get the size. return; } // Create an extra parameter that aligns the bottom of the expanded ad to the // bottom of the banner ad. const adRequest = AdRequest(extras: { "collapsible": "bottom", }); BannerAd( adUnitId: adUnitId, request: adRequest, size: size, listener: const BannerAdListener() ).load(); } ``` -------------------------------- ### Add Liftoff Monetize SDK via local path to pubspec.yaml Source: https://developers.google.com/admob/flutter/mediation/liftoff-monetize Reference the Liftoff Monetize SDK in your pubspec.yaml file using a local path for manual integration. ```yaml dependencies: gma_mediation_liftoffmonetize: path: path/to/local/package ``` -------------------------------- ### Get Portrait Inline Adaptive Banner Ad Size Source: https://developers.google.com/admob/flutter/banner/inline-adaptive Use this method to get an inline adaptive ad size specifically for portrait orientation. It requires the width of the view in pixels. ```dart final adWidth = MediaQuery.of(context).size.width.toInt(); final adSize = AdSize.getPortraitInlineAdaptiveBannerAdSize(adWidth); ``` -------------------------------- ### Add Maio SDK Dependency (Manual Integration) Source: https://developers.google.com/admob/flutter/mediation/maio Reference the maio SDK and adapter in your pubspec.yaml file when performing a manual integration. ```yaml dependencies: gma_mediation_maio: path: path/to/local/package ``` -------------------------------- ### Get Landscape Inline Adaptive Banner Ad Size Source: https://developers.google.com/admob/flutter/banner/inline-adaptive Use this method to get an inline adaptive ad size specifically for landscape orientation. It requires the width of the view in pixels. ```dart final adWidth = MediaQuery.of(context).size.width.toInt(); final adSize = AdSize.getLandscapeInlineAdaptiveBannerAdSize(adWidth); ``` -------------------------------- ### Show App Open Ad with Callbacks Source: https://developers.google.com/admob/flutter/app-open Shows an available AppOpenAd and registers callbacks for ad events like showing, failing to show, and dismissing the ad. It also handles loading a new ad after dismissal. ```dart public class AppOpenAdManager { ... public void showAdIfAvailable() { if (!isAdAvailable) { print('Tried to show ad before available.'); loadAd(); return; } if (_isShowingAd) { print('Tried to show ad while already showing an ad.'); return; } // Set the fullScreenContentCallback and show the ad. _appOpenAd!.fullScreenContentCallback = FullScreenContentCallback( onAdShowedFullScreenContent: (ad) { _isShowingAd = true; print('$ad onAdShowedFullScreenContent'); }, onAdFailedToShowFullScreenContent: (ad, error) { print('$ad onAdFailedToShowFullScreenContent: $error'); _isShowingAd = false; ad.dispose(); _appOpenAd = null; }, onAdDismissedFullScreenContent: (ad) { print('$ad onAdDismissedFullScreenContent'); _isShowingAd = false; ad.dispose(); _appOpenAd = null; loadAd(); }, ); } } ``` -------------------------------- ### Get Current Orientation Inline Adaptive Banner Ad Size Source: https://developers.google.com/admob/flutter/banner/inline-adaptive Use this method to get an inline adaptive ad size for the current device orientation. It requires the width of the view in pixels. ```dart final adWidth = MediaQuery.of(context).size.width.toInt(); final adSize = AdSize.getCurrentOrientationInlineAdaptiveBannerAdSize(adWidth); ``` -------------------------------- ### Get Inline Adaptive Banner Ad Size with Max Height Source: https://developers.google.com/admob/flutter/banner/inline-adaptive Use this method to get an inline adaptive ad size with a specified maximum height. It requires the width of the view and the maximum height in pixels. ```dart final adWidth = MediaQuery.of(context).size.width.toInt(); final adHeight = 100; // Example max height final adSize = AdSize.getInlineAdaptiveBannerAdSize(adWidth, adHeight); ``` -------------------------------- ### Add Mintegral Dependency via pub.dev Source: https://developers.google.com/admob/flutter/mediation/mintegral Add the Mintegral SDK and adapter dependency to your pubspec.yaml file for integration through pub.dev. ```yaml dependencies: gma_mediation_mintegral: ^2.1.0 ``` -------------------------------- ### Add Maio SDK Dependency (pub.dev) Source: https://developers.google.com/admob/flutter/mediation/maio Add the maio SDK and adapter dependency to your pubspec.yaml file for integration through pub.dev. ```yaml dependencies: gma_mediation_maio: ^1.1.4 ``` -------------------------------- ### Get Anchored Adaptive Banner Ad Size Source: https://developers.google.com/admob/flutter/banner Obtain an `AdSize` object for an anchored adaptive banner ad based on the screen width. This is a prerequisite for loading the ad. ```dart // Get an AnchoredAdaptiveBannerAdSize before loading the ad. final size = await AdSize.getLargeAnchoredAdaptiveBannerAdSize( MediaQuery.sizeOf(context).width.truncate(), ); main.dart ``` -------------------------------- ### Implement NativeAdFactory in iOS Source: https://developers.google.com/admob/flutter/native/platforms This Objective-C snippet demonstrates the implementation of the FLTNativeAdFactory protocol for iOS. It includes the createNativeAd:customOptions: method to create and populate a GADNativeAdView with native ad assets. ```objectivec #import "FLTGoogleMobileAdsPlugin.h" /** * The example NativeAdView.xib can be found at * github.com/googleads/googleads-mobile-flutter/blob/main/packages/google_mobile_ads/ * example/ios/Runner/NativeAdView.xib */ @interface NativeAdFactoryExample : NSObject @end @implementation NativeAdFactoryExample - (GADNativeAdView *)createNativeAd:(GADNativeAd *)nativeAd customOptions:(NSDictionary *)customOptions { // Create and place the ad in the view hierarchy. GADNativeAdView *adView = [[NSBundle mainBundle] loadNibNamed:@ ``` -------------------------------- ### Create and Load BannerAd Source: https://developers.google.com/admob/flutter/banner/inline-adaptive This snippet shows how to create a BannerAd object with an ad unit ID, an adaptive ad size, and an ad request, and then load the ad. ```dart final bannerAd = BannerAd( adUnitId: 'YOUR_AD_UNIT_ID', size: adSize, // adSize obtained from previous steps request: const AdRequest(), listener: BannerAdListener( onAdLoaded: (ad) { // Update the AdWidget container height in the onAdLoaded callback // final updatedAdSize = ad.getPlatformAdSize(); // setState(() { // _containerHeight = updatedAdSize.height.toDouble(); // }); }, onAdFailedToLoad: (ad, err) { ad.dispose(); }, ), ); bannerAd.load(); ``` -------------------------------- ### Bypass GADApplicationIdentifier Check on iOS Source: https://developers.google.com/admob/flutter/webview Update your Runner/Info.plist file with this key and string value to bypass the GADApplicationIdentifier check for the WebView API for Ads. This prevents potential GADInvalidInitializationException errors on app start. ```xml GADIntegrationManager webview ``` -------------------------------- ### Add i-mobile SDK Dependency (pub.dev) Source: https://developers.google.com/admob/flutter/mediation/imobile Add the i-mobile SDK and adapter dependency to your pubspec.yaml file for integration via pub.dev. ```yaml dependencies: gma_mediation_imobile: ^1.0.3 ``` -------------------------------- ### Bypass Application ID Check on Android Source: https://developers.google.com/admob/flutter/webview Add this meta-data tag to your AndroidManifest.xml to bypass the application identifier check for the WebView API for Ads. This prevents potential IllegalStateException errors on app start. ```xml ``` -------------------------------- ### Reset Consent State for Testing Source: https://developers.google.com/admob/flutter/privacy Resets the UMP SDK's consent state to simulate a user's first install experience. This method is intended for testing purposes only and should not be used in production. ```dart ConsentInformation.instance.reset(); ``` -------------------------------- ### Register FLTMediationNetworkExtrasProvider Source: https://developers.google.com/admob/flutter/mediation/network-specific-parameters Register your custom network extras provider with `FLTGoogleMobileAdsPlugin` in your `AppDelegate` to enable it for ad requests. ```objective-c @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [GeneratedPluginRegistrant registerWithRegistry:self]; // Register your network extras provider if you want to provide // network extras to specific ad requests. MyFLTMediationNetworkExtrasProvider *networkExtrasProvider = [[MyFLTMediationNetworkExtrasProvider alloc] init]; [FLTGoogleMobileAdsPlugin registerMediationNetworkExtrasProvider:networkExtrasProvider registry:self]; return [super application:application didFinishLaunchingWithOptions:launchOptions]; } @end ``` -------------------------------- ### Add Liftoff Monetize SDK to pubspec.yaml Source: https://developers.google.com/admob/flutter/mediation/liftoff-monetize Add the Liftoff Monetize SDK dependency to your Flutter project's pubspec.yaml file for integration through pub.dev. ```yaml dependencies: gma_mediation_liftoffmonetize: ^1.5.0 ``` -------------------------------- ### Add Chartboost Dependency (pub.dev) Source: https://developers.google.com/admob/flutter/mediation/chartboost Add the Chartboost SDK and adapter dependency to your pubspec.yaml file for integration via pub.dev. ```yaml dependencies: gma_mediation_chartboost: ^1.5.0 ``` -------------------------------- ### Check if a Loaded Banner Ad is Collapsible Source: https://developers.google.com/admob/flutter/banner/collapsible This example shows how to check if the last loaded banner ad is collapsible using the `isCollapsible` property within the `BannerAdListener`. This is useful for understanding the ad's behavior after it loads. ```dart BannerAd( // ... listener: BannerAdListener( onAdLoaded: (ad) { final bannerAd = ad as BannerAd; final isCollapsible = bannerAd.isCollapsible; print('The last loaded banner is ${isCollapsible ? "" : "not"} collapsible.'); }, ), ).load(); ``` -------------------------------- ### Implement NativeAdFactory Source: https://developers.google.com/admob/flutter/native/platforms This class implements the NativeAdFactory interface to create and configure a custom NativeAdView. It inflates a layout, sets various ad assets like headline, body, and media, and handles cases where assets might be missing. Use this when you need a custom layout for your native ads. ```java package io.flutter.plugins.googlemobileadsexample; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import com.google.android.gms.ads.nativead.MediaView; import com.google.android.gms.ads.nativead.NativeAd; import com.google.android.gms.ads.nativead.NativeAdView; import io.flutter.plugins.googlemobileads.GoogleMobileAdsPlugin.NativeAdFactory; import java.util.Map; /** * my_native_ad.xml can be found at * github.com/googleads/googleads-mobile-flutter/blob/main/packages/google_mobile_ads/ * example/android/app/src/main/res/layout/my_native_ad.xml */ class NativeAdFactoryExample implements NativeAdFactory { private final LayoutInflater layoutInflater; NativeAdFactoryExample(LayoutInflater layoutInflater) { this.layoutInflater = layoutInflater; } @Override public NativeAdView createNativeAd( NativeAd nativeAd, Map customOptions) { final NativeAdView adView = (NativeAdView) layoutInflater.inflate(R.layout.my_native_ad, null); // Set the media view. adView.setMediaView((MediaView) adView.findViewById(R.id.ad_media)); // Set other ad assets. adView.setHeadlineView(adView.findViewById(R.id.ad_headline)); adView.setBodyView(adView.findViewById(R.id.ad_body)); adView.setCallToActionView(adView.findViewById(R.id.ad_call_to_action)); adView.setIconView(adView.findViewById(R.id.ad_app_icon)); adView.setPriceView(adView.findViewById(R.id.ad_price)); adView.setStarRatingView(adView.findViewById(R.id.ad_stars)); adView.setStoreView(adView.findViewById(R.id.ad_store)); adView.setAdvertiserView(adView.findViewById(R.id.ad_advertiser)); // The headline and mediaContent are guaranteed to be in every NativeAd. ((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline()); adView.getMediaView().setMediaContent(nativeAd.getMediaContent()); // These assets aren't guaranteed to be in every NativeAd, so it's important to // check before trying to display them. if (nativeAd.getBody() == null) { adView.getBodyView().setVisibility(View.INVISIBLE); } else { adView.getBodyView().setVisibility(View.VISIBLE); ((TextView) adView.getBodyView()).setText(nativeAd.getBody()); } if (nativeAd.getCallToAction() == null) { adView.getCallToActionView().setVisibility(View.INVISIBLE); } else { adView.getCallToActionView().setVisibility(View.VISIBLE); ((Button) adView.getCallToActionView()).setText(nativeAd.getCallToAction()); } if (nativeAd.getIcon() == null) { adView.getIconView().setVisibility(View.GONE); } else { ((ImageView) adView.getIconView()).setImageDrawable(nativeAd.getIcon().getDrawable()); adView.getIconView().setVisibility(View.VISIBLE); } if (nativeAd.getPrice() == null) { adView.getPriceView().setVisibility(View.INVISIBLE); } else { adView.getPriceView().setVisibility(View.VISIBLE); ((TextView) adView.getPriceView()).setText(nativeAd.getPrice()); } if (nativeAd.getStore() == null) { adView.getStoreView().setVisibility(View.INVISIBLE); } else { adView.getStoreView().setVisibility(View.VISIBLE); ((TextView) adView.getStoreView()).setText(nativeAd.getStore()); } if (nativeAd.getStarRating() == null) { adView.getStarRatingView().setVisibility(View.INVISIBLE); } else { ((RatingBar) adView.getStarRatingView()).setRating(nativeAd.getStarRating() .floatValue()); adView.getStarRatingView().setVisibility(View.VISIBLE); } if (nativeAd.getAdvertiser() == null) { adView.getAdvertiserView().setVisibility(View.INVISIBLE); } else { adView.getAdvertiserView().setVisibility(View.VISIBLE); ((TextView) adView.getAdvertiserView()).setText(nativeAd.getAdvertiser()); } // This method tells Google Mobile Ads Flutter Plugin that you have finished populating your // native ad view with this native ad. adView.setNativeAd(nativeAd); return adView; } } ``` -------------------------------- ### Handling Native Ad Events Source: https://developers.google.com/admob/flutter/native/templates Implement NativeAdListener to receive callbacks for various native ad events such as loading, failure, clicks, impressions, and closures. This snippet shows the setup within a Flutter state class. ```dart class NativeExampleState extends State { NativeAd? _nativeAd; bool _nativeAdIsLoaded = false; // TODO: replace this test ad unit with your own ad unit. final String _adUnitId = Platform.isAndroid ? 'ca-app-pub-3940256099942544/2247696110' : 'ca-app-pub-3940256099942544/3986624511'; /// Loads a native ad. void loadAd() { _nativeAd = NativeAd( adUnitId: _adUnitId, listener: NativeAdListener( onAdLoaded: (ad) { print('$NativeAd loaded.'); setState(() { _nativeAdIsLoaded = true; }); }, onAdFailedToLoad: (ad, error) { // Dispose the ad here to free resources. print('$NativeAd failedToLoad: $error'); ad.dispose(); }, // Called when a click is recorded for a NativeAd. onAdClicked: (ad) {}, // Called when an impression occurs on the ad. onAdImpression: (ad) {}, // Called when an ad removes an overlay that covers the screen. onAdClosed: (ad) {}, // Called when an ad opens an overlay that covers the screen. onAdOpened: (ad) {}, // For iOS only. Called before dismissing a full screen view onAdWillDismissScreen: (ad) {}, // Called when an ad receives revenue value. onPaidEvent: (ad, valueMicros, precision, currencyCode) {}, ), request: const AdRequest(), // Styling nativeTemplateStyle: NativeTemplateStyle( // Required: Choose a template. templateType: TemplateType.medium, // Optional: Customize the ad's style. mainBackgroundColor: Colors.purple, cornerRadius: 10.0, callToActionTextStyle: NativeTemplateTextStyle( textColor: Colors.cyan, backgroundColor: Colors.red, style: NativeTemplateFontStyle.monospace, size: 16.0), primaryTextStyle: NativeTemplateTextStyle( textColor: Colors.red, backgroundColor: Colors.cyan, style: NativeTemplateFontStyle.italic, size: 16.0), secondaryTextStyle: NativeTemplateTextStyle( textColor: Colors.green, backgroundColor: Colors.black, style: NativeTemplateFontStyle.bold, size: 16.0), tertiaryTextStyle: NativeTemplateTextStyle( textColor: Colors.brown, backgroundColor: Colors.amber, style: NativeTemplateFontStyle.normal, size: 16.0))) ..load(); } } ``` -------------------------------- ### Set US States Privacy Law Consent (OptInSale) Source: https://developers.google.com/admob/flutter/mediation/chartboost Use the Chartboost.AddDataUseConsent() method to set data use consent to OptInSale, recommended before requesting ads. ```csharp using GoogleMobileAds.Api.Mediation.Chartboost; // ... Chartboost.AddDataUseConsent(CBCCPADataUseConsent.OptInSale); ``` -------------------------------- ### Add AppLovin Dependency via pub.dev Source: https://developers.google.com/admob/flutter/mediation/applovin Add the AppLovin SDK and adapter dependency to your pubspec.yaml file for integration through pub.dev. ```yaml dependencies: gma_mediation_applovin: ^2.6.1 ``` -------------------------------- ### Show Rewarded Ad Source: https://developers.google.com/admob/flutter/rewarded Call the show() method on a loaded RewardedAd to display it. Implement the onUserEarnedReward callback to provide rewards to the user. This ad is displayed as an overlay and cannot be added to the widget tree. ```dart _rewardedAd?.show( onUserEarnedReward: (AdWithoutView ad, RewardItem rewardItem) { debugPrint( 'Reward amount: ${rewardItem.amount}', ); }, ); main.dart ``` -------------------------------- ### Implement BannerAdListener Source: https://developers.google.com/admob/flutter/banner Implement each method of BannerAdListener to listen for lifecycle events like ad opening, closing, impressions, and clicks. Logs messages to the console for each event. ```dart onAdOpened: (Ad ad) { // Called when an ad opens an overlay that covers the screen. debugPrint("Ad was opened."); }, onAdClosed: (Ad ad) { // Called when an ad removes an overlay that covers the screen. debugPrint("Ad was closed."); }, onAdImpression: (Ad ad) { // Called when an impression occurs on the ad. debugPrint("Ad recorded an impression."); }, onAdClicked: (Ad ad) { // Called when an a click event occurs on the ad. debugPrint("Ad was clicked."); }, onAdWillDismissScreen: (Ad ad) { // iOS only. Called before dismissing a full screen view. debugPrint("Ad will be dismissed."); } ``` -------------------------------- ### Implement FLTMediationNetworkExtrasProvider Source: https://developers.google.com/admob/flutter/mediation/network-specific-parameters Implement the `FLTMediationNetworkExtrasProvider` protocol to provide custom network extras. This method is called for each ad request and can pass specific extras to adapters like AppLovin. ```objective-c @implementation MyFLTMediationNetworkExtrasProvider - (NSArray> *_Nullable)getMediationExtras:(NSString *_Nonnull)adUnitId mediationExtrasIdentifier: (NSString *_Nullable)mediationExtrasIdentifier { // This example passes extras to the AppLovin adapter. // This method is called with the ad unit of the associated ad request, and // an optional string parameter which comes from the dart ad request object. GADMAdapterAppLovinExtras *appLovinExtras = [[GADMAdapterAppLovinExtras alloc] init]; appLovinExtras.muteAudio = NO; // Note: You can pass extras to multiple adapters by adding more entries. return @[ appLovinExtras ]; } @end ``` -------------------------------- ### Add Repositories to build.gradle (Android) Source: https://developers.google.com/admob/flutter/choose-networks For Android projects, add these repositories to the build.gradle file located in your project's android directory. ```gradle allprojects { repositories { google() mavenCentral() } } ``` -------------------------------- ### Add Mintegral Dependency via Local Path Source: https://developers.google.com/admob/flutter/mediation/mintegral Reference the Mintegral plugin in your pubspec.yaml file by adding the dependency with a local path for manual integration. ```yaml dependencies: gma_mediation_mintegral: path: path/to/local/package ``` -------------------------------- ### Show Rewarded Interstitial Ad Source: https://developers.google.com/admob/flutter/rewarded-interstitial Call the `show()` method on a loaded `RewardedInterstitialAd` to display it. Implement the `onUserEarnedReward` callback to provide the user with their reward. ```dart _rewardedInterstitialAd?.show( onUserEarnedReward: (AdWithoutView view, RewardItem rewardItem) { debugPrint('Reward amount: ${rewardItem.amount}'); }, ); ``` -------------------------------- ### Add BidMachine Dependency to pubspec.yaml Source: https://developers.google.com/admob/flutter/mediation/bidmachine Add the BidMachine SDK and adapter dependency to your Flutter project's pubspec.yaml file to enable integration. ```yaml dependencies: gma_mediation_bidmachine: ^1.3.2 ``` -------------------------------- ### Instantiate AdWidget for Native Ad Source: https://developers.google.com/admob/flutter/native/platforms Instantiate an AdWidget with a loaded NativeAd. On iOS, ensure the widget is within a container with specified width and height for proper display. ```dart final Container adContainer = Container( alignment: Alignment.center, child: AdWidget adWidget = AdWidget(ad: _nativeAd!), width: WIDTH, height: HEIGHT, ); ``` -------------------------------- ### Add LINE Ads Network Dependency (pub.dev) Source: https://developers.google.com/admob/flutter/mediation/line Add the LINE Ads Network SDK and adapter dependency to your pubspec.yaml file using the latest versions from pub.dev. ```yaml dependencies: gma_mediation_line: ^2.1.0 ``` -------------------------------- ### Add Moloco Dependency via pub.dev Source: https://developers.google.com/admob/flutter/mediation/moloco Add the Moloco Ads SDK and adapter dependency to your pubspec.yaml file using the latest versions from pub.dev. ```yaml dependencies: gma_mediation_moloco: ^3.4.0 ``` -------------------------------- ### Handle Interstitial Ad Lifecycle Events Source: https://developers.google.com/admob/flutter/interstitial Sets up callbacks to listen for various lifecycle events of an interstitial ad, such as when it's shown, fails to show, or is dismissed. Ensures proper disposal of the ad resources. ```dart ad.fullScreenContentCallback = FullScreenContentCallback( onAdShowedFullScreenContent: (ad) { // Called when the ad showed the full screen content. debugPrint('Ad showed full screen content.'); }, onAdFailedToShowFullScreenContent: (ad, err) { // Called when the ad failed to show full screen content. debugPrint('Ad failed to show full screen content with error: $err'); // Dispose the ad here to free resources. ad.dispose(); }, onAdDismissedFullScreenContent: (ad) { // Called when the ad dismissed full screen content. debugPrint('Ad was dismissed.'); // Dispose the ad here to free resources. ad.dispose(); }, onAdImpression: (ad) { // Called when an impression occurs on the ad. debugPrint('Ad recorded an impression.'); }, onAdClicked: (ad) { // Called when a click is recorded for an ad. debugPrint('Ad was clicked.'); }, ); ``` -------------------------------- ### Display Banner Ad Widget Source: https://developers.google.com/admob/flutter/banner Instantiate an AdWidget with a loaded BannerAd and display it. Ensure the widget has a specified width and height, especially on iOS, by placing it within a SizedBox that matches the ad's dimensions. ```dart if (_bannerAd != null) Align( alignment: Alignment.bottomCenter, child: SafeArea( child: SizedBox( width: _bannerAd!.size.width.toDouble(), height: _bannerAd!.size.height.toDouble(), child: AdWidget(ad: _bannerAd!), ), ), ) ``` -------------------------------- ### Add Meta Audience Network SDK Dependency Source: https://developers.google.com/admob/flutter/mediation/meta Add the Meta Audience Network SDK and adapter dependency to your pubspec.yaml file for integration through pub.dev. ```yaml dependencies: gma_mediation_meta: ^1.5.2 ``` -------------------------------- ### Add BidMachine Mediation Dependency Source: https://developers.google.com/admob/flutter/mediation/bidmachine Reference the BidMachine mediation plugin in your `pubspec.yaml` file by adding the local package dependency. ```yaml dependencies: gma_mediation_bidmachine: path: path/to/local/package ```