Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

google mobile ads for flutter

this guide is intended for publishers who want to monetize a flutter app.

integrating google mobile ads sdk into a flutter app, which you will do here, is the first step towards displaying admob ads and earning revenue. once the integration is complete, you can choose an ad format to get detailed implementation steps.

the google mobile ads sdk for flutter currently supports loading and displaying banner, interstitial (full-screen), native ads, and rewarded video ads.

note: this plugin also contains support for google ad manager. if you are interested in creating and loading an ad with ad manager, you may follow the same prerequisites, platform setup, mobile ads sdk initialization steps outlined in this doc, and then see creating and loading an ad with ad manager for further instructions.

see also the codelab for inline ads in flutter for a detailed guide on setting
inline banner and native ads.

prerequisites

  • flutter 1.22.0 or higher
  • android
    • android studio 3.2 or higher
    • target android api level 19 or higher
    • set compilesdkversion to 28 or higher
    • android gradle plugin 4.1 or higher (this is the version supported by flutter out of the box)
  • ios
  • recommended: create an admob account and register an android and/or ios app (to show live ads on a published app, it is required to register that app).

import the mobile ads sdk

platform specific setup

ios

update your info.plist

update your app’s ios/runner/info.plist file to add two keys:

  • a gadapplicationidentifier key with a string value of your admob app id (identified in the admob ui).
  • a skadnetworkitems key with google’s skadnetworkidentifier value of cstr6suwn9.skadnetwork.
<key>gadapplicationidentifier</key>
<string>ca-app-pub-3940256099942544~1458002511</string>
<key>skadnetworkitems</key>
  <array>
    <dict>
      <key>skadnetworkidentifier</key>
      <string>cstr6suwn9.skadnetwork</string>
    </dict>
  </array>

see https://developers.google.com/admob/ios/quick-start#update_your_infoplist for more information about configuring info.plist and setting up your app id.

android

update androidmanifest.xml

the admob app id must be included in the androidmanifest.xml. failure to do so will result in a crash on launch of an app.

add the admob app id (identified in the admob ui) to the app’s android/app/src/main/androidmanifest.xml file by adding a <meta-data> tag with name com.google.android.gms.ads.application_id, as shown below. you can find your app id in the admob ui. for android:value insert your own admob app id in quotes, as shown below.

<manifest>
    <application>
        <!-- sample admob app id: ca-app-pub-3940256099942544~3347511713 -->
        <meta-data
            android:name="com.google.android.gms.ads.application_id"
            android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>
    </application>
</manifest>

the same value when you initialize the plugin in your dart code.

see https://goo.gl/fq2neu for more information about configuring androidmanifest.xml and setting up the app id.

initialize the mobile ads sdk

before loading ads, have your app initialize the mobile ads sdk by calling mobileads.instance.initialize() which initializes the sdk and returns a future that finishes once initialization is complete (or after a 30-second timeout). this needs to be done only once, ideally right before running the app.

import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:flutter/material.dart';

void main() {
  widgetsflutterbinding.ensureinitialized();
  mobileads.instance.initialize();

  runapp(myapp());
}

class myapp extends statefulwidget {
  @override
  myappstate createstate() => myappstate();
}

class myappstate extends state<myapp> {
  @override
  void initstate() {
    super.initstate();
    // load ads.
  }
}

select an ad format

the mobile ads sdk is now imported and you’re ready to implement an ad. admob offers a number of different ad formats, so you can choose the one that best fits your app’s user experience.

  • banner
    • rectangular ads that appear at the top or bottom of the device screen. banner ads stay on screen while users are interacting with the app, and can refresh automatically after a certain period of time. if you’re new to mobile advertising, they’re a great place to start.
  • interstitial
    • full-screen ads that cover the interface of an app until closed by the user. they’re best used at natural pauses in the flow of an app’s execution, such as between levels of a game or just after a task is completed.
  • native ads
    • customizable ads that match the look and feel of your app. you decide how and where they’re placed, so the layout is more consistent with your app’s design.
  • rewarded
    • ads that reward users for watching short videos and interacting with playable ads and surveys. good for monetizing free-to-play users.

banner ads

banner ads occupy a spot within an app’s layout, either at the top or bottom of the device screen. they stay on screen while users are interacting with the app, and can refresh automatically after a certain period of time.

this guide shows you how to integrate banner ads from admob into a flutter app. in addition to code snippets and instructions, it also includes information about sizing banners properly and links to additional resources.

see also the codelab for inline ads in flutter for a detailed guide on setting up banner ads.

always test with test ads

when building and testing your apps, make sure you use test ads rather than live, production ads. failure to do so can lead to suspension of your account.

the easiest way to load test ads is to use our dedicated test ad unit id for banners:

it’s been specially configured to return test ads for every request, and you’re free to use it in your own apps while coding, testing, and debugging. just make sure you replace it with your own ad unit id before publishing your app.

instantiate a banner ad

a bannerad requires an adunitid, an adsize, an adrequest, and a banneradlistener. an example is shown below as well as more information on each parameter following.

final bannerad mybanner = bannerad(
  adunitid: '<ad unit id>',
  size: adsize.banner,
  request: adrequest(),
  listener: banneradlistener(),
);

banner sizes

the table below lists the standard banner sizes.

size in dp (wxh) description adsize constant
320×50 standard banner banner
320×100 large banner largebanner
320×250 medium rectangle mediumrectangle
468×60 full-size banner fullbanner
728×90 leaderboard leaderboard
screen width x 32|50|90 smart banner use getsmartbanner(orientation)
provided width x adaptive height adaptive banner use getanchoredadaptivebanneradsize(orientation, int)

to define a custom banner size, set your desired adsize, as shown here:

final adsize adsize = adsize(300, 50);

banner ad events

through the use of banneradlistener, you can listen for lifecycle events, such as when an ad is loaded. this example implements each method and logs a message to the console:

final banneradlistener listener = banneradlistener(
 // called when an ad is successfully received.
 onadloaded: (ad ad) => print('ad loaded.'),
 // called when an ad request failed.
 onadfailedtoload: (ad ad, loadaderror error) {
   // dispose the ad here to free resources.
   ad.dispose();
   print('ad failed to load: $error');
 },
 // called when an ad opens an overlay that covers the screen.
 onadopened: (ad ad) => print('ad opened.'),
 // called when an ad removes an overlay that covers the screen.
 onadclosed: (ad ad) => print('ad closed.'),
 // called when an impression occurs on the ad.
 onadimpression: (ad ad) => print('ad impression.'),
);

load banner ad

after a bannerad is instantiated, load() must be called before it can be shown on the screen.

mybanner.load();

display a banner ad

to display a bannerad as a widget, you must instantiate an adwidget with a supported ad after calling load(). you can create the widget before calling load(), but load() must be called before adding it to the widget tree.

final adwidget adwidget = adwidget(ad: mybanner);

adwidget inherits from flutter’s widget class and can be used as any other widget. on ios, make sure you place the widget in a widget with a specified width and height. otherwise, your ad may not be displayed. a bannerad can be placed in a container with a size that matches the ad:

final container adcontainer = container(
  alignment: alignment.center,
  child: adwidget,
  width: mybanner.size.width.todouble(),
  height: mybanner.size.height.todouble(),
);

once an ad has called load(), it must call dispose() when access to it is no longer needed. the best practice for when to call dispose() is either after the adwidget is removed from the widget tree or in the adlistener.onadfailedtoload callback.

that’s it! your app is now ready to display banner ads.

interstitial ad

interstitial ads are full-screen ads that cover the interface of their host app. they’re typically displayed at natural transition points in the flow of an app, such as between activities or during the pause between levels in a game. when an app shows an interstitial ad, the user has the choice to either tap on the ad and continue to its destination or close it and return to the app.

this guide explains how to integrate interstitial ads into a flutter app.

always test with test ads

when building and testing your apps, make sure you use test ads rather than live, production ads. failure to do so can lead to suspension of your account.

the easiest way to load test ads is to use our dedicated test ad unit id for interstitials:

it’s been specially configured to return test ads for every request, and you’re free to use it in your own apps while coding, testing, and debugging. just make sure you replace it with your own ad unit id before publishing your app.

load an interstitial ad

loading an interstitialad requires an adunitid, an adrequest, and an interstitialadloadcallback. an example is shown below as well as more information on each parameter following.


interstitialad.load(
  adunitid: '<ad unit id>',
  request: adrequest(),
  adloadcallback: interstitialadloadcallback(
    onadloaded: (interstitialad ad) {
      // keep a reference to the ad so you can show it later.
      this._interstitialad = ad;
    },
    onadfailedtoload: (loadaderror error) {
      print('interstitialad failed to load: $error');
    },
  ));

interstitial ad events

through the use of fullscreencontentcallback, you can listen for lifecycle events, such as when the ad is shown or dismissed.
set interstitialad.fullscreencontentcallback before showing the ad to receive notifications for these events. this example implements each method and logs a message to the console:

interstitialad.fullscreencontentcallback = fullscreencontentcallback(
  onadshowedfullscreencontent: (interstitialad ad) =>
     print('$ad onadshowedfullscreencontent.'),
  onaddismissedfullscreencontent: (interstitialad ad) {
    print('$ad onaddismissedfullscreencontent.');
    ad.dispose();
  },
  onadfailedtoshowfullscreencontent: (interstitialad ad, aderror error) {
    print('$ad onadfailedtoshowfullscreencontent: $error');
    ad.dispose();
  },
  onadimpression: (interstitialad ad) => print('$ad impression occurred.'),
);

display an interstitial ad

an interstitialad is displayed as an overlay on top of all app content and is statically placed. which means it can not be added to the flutter widget tree. you can choose when to show the ad by calling show().

myinterstitial.show();

once show() is called, an ad displayed this way can’t be removed programmatically and requires user input. an interstitialad can only be shown once. subsequent calls to show will trigger onadfailedtoshowfullscreencontent.

once an ad has called load(), it must call dispose() when access to it is no longer needed. the best practice for when to call dispose() is in the fullscreencontentcallback.onaddismissedfullscreencontent and fullscreencontentcallback.onadfailedtoshowfullscreencontent callbacks.

that’s it! your app is now ready to display interstitial ads.

next steps

native ads

native ads are ad assets that are presented to users via ui components that are native to the platform. they’re shown using the same types of views with which you’re already building your layouts, and can be formatted to match the visual design of the user experience in which they live. in coding terms, this means that when a native ad loads, your app receives a nativead object that contains its assets, and the app (rather than the google mobile ads sdk) is then responsible for displaying them.

broadly speaking, there are two parts to successfully implementing native ads: loading an ad via the sdk and displaying the ad content in your app. this guide is concerned with using the sdk to load native ads.

see also the codelab for inline ads in flutter for a detailed guide on setting up native ads.

platform setup

native ads are presented to users via ui components that are native to the platform. (e.g. a view on android or a uiview on ios).

since native ads require ui components native to a platform, this feature requires additional setup for android and ios:

android

the android implementation of the google mobile ads plugin requires a class that implements a nativeadfactory. a nativeadfactory contains a method that takes a nativead and custom options and returns a nativeadview. the nativeadview is what will be displayed in your app.

you can implement this in your mainactivity.java or create a separate class in the same directory as mainactivity.java as seen below:

package my.app.path;

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;

class nativeadfactoryexample implements nativeadfactory {
  @override
  public nativeadview createnativead(
      nativead nativead, map<string, object> customoptions) {
    // create nativeadview
  }
}

each nativeadfactory needs to be registered with a factoryid, a unique string identifier, in mainactivity.configureflutterengine(flutterengine). a nativeadfactory can be implemented and registered for each unique native ad layout used by your app or a single one can handle all layouts. the nativeadfactory should also be unregistered in cleanupflutterengine(engine) when building with add-to-app.

mainactivity.java should look similar to:

package my.app.path;

import io.flutter.embedding.android.flutteractivity;
import io.flutter.embedding.engine.flutterengine;
import io.flutter.plugins.googlemobileads.googlemobileadsplugin;

public class mainactivity extends flutteractivity {
  @override
  public void configureflutterengine(flutterengine flutterengine) {
    flutterengine.getplugins().add(new googlemobileadsplugin());
   super.configureflutterengine(flutterengine);

    googlemobileadsplugin.registernativeadfactory(flutterengine, "adfactoryexample", nativeadfactoryexample());
  }

  @override
  public void cleanupflutterengine(flutterengine flutterengine) {
    googlemobileadsplugin.unregisternativeadfactory(flutterengine, "adfactoryexample");
  }
}

when creating the nativead in dart, the factoryid will need to match the one used to add the factory to googlemobileadsplugin. in the above code snippet, adfactoryexample is the name of the factoryid. an example nativeadfactory follows:

package io.flutter.plugins.googlemobileadsexample;

import android.graphics.color;
import android.view.layoutinflater;
import android.widget.textview;
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
/* https://github.com/googleads/googleads-mobile-flutter/tree/master/packages/google_mobile_ads/example/android/app/src/main/res/layout
*/
class nativeadfactoryexample implements nativeadfactory {
 private final layoutinflater layoutinflater;

 nativeadfactoryexample(layoutinflater layoutinflater) {
   this.layoutinflater = layoutinflater;
 }

 @override
 public nativeadview createnativead(
     nativead nativead, map<string, object> customoptions) {
   final nativeadview adview =
       (nativeadview) layoutinflater.inflate(r.layout.my_native_ad, null);
   final textview headlineview = adview.findviewbyid(r.id.ad_headline);
   final textview bodyview = adview.findviewbyid(r.id.ad_body);

   headlineview.settext(nativead.getheadline());
   bodyview.settext(nativead.getbody());

   adview.setbackgroundcolor(color.yellow);

   adview.setnativead(nativead);
   adview.setbodyview(bodyview);
   adview.setheadlineview(headlineview);
   return adview;
 }
}

ios

the ios implementation of the google mobile ads plugin requires a class that implements a fltnativeadfactory. a fltnativeadfactory contains a method that takes a gadnativead and custom options and returns a gadnativeadview. the gadnativeadview is what will be displayed in your app.

the fltnativeadfactory protocol can be implemented by appdelegate or a separate class could be created as seen below:

/* appdelegate.m */
#import "fltgooglemobileadsplugin.h"
@interface nativeadfactoryexample : nsobject<fltnativeadfactory>
@end

@implementation nativeadfactoryexample
- (gadnativeadview *)createnativead:(gadnativead *)nativead
                             customoptions:(nsdictionary *)customoptions {
  // create gadnativeadview
}
@end

each fltnativeadfactory needs to be registered with a factoryid, a unique string identifier, in registernativeadfactory:factoryid:nativeadfactory:. a fltnativeadfactory can be implemented and registered for each unique native ad layout used by your app or a single one can handle all layouts. this is done by importing fltgooglemobileadsplugin.h and calling registernativeadfactory:factoryid:nativeadfactory: with a flutterpluginregistry, a unique identifier for the factory, and the factory itself. the factory also must be added after [generatedpluginregistrant registerwithregistry:self]; has been called.

if this is done in appdelegate.m, it should look similar to:

#import "fltgooglemobileadsplugin.h"

@implementation appdelegate
- (bool)application:(uiapplication *)application
    didfinishlaunchingwithoptions:(nsdictionary *)launchoptions {
  [generatedpluginregistrant registerwithregistry:self];

  nativeadfactoryexample *nativeadfactory = [[nativeadfactoryexample alloc] init];
  [fltgooglemobileadsplugin registernativeadfactory:self
                                        factoryid:@"adfactoryexample"
                                  nativeadfactory:nativeadfactory];

  return [super application:application didfinishlaunchingwithoptions:launchoptions];
}
@end

when creating the nativead in dart, the factoryid will need to match the one used to add the factory to fltgooglemobileadsplugin. in the above code snippet, adfactoryexample is the name of the factoryid.an examplefltnativeadfactory` follows:

// the example nativeadview.xib can be found at
/* https://github.com/googleads/googleads-mobile-flutter/blob/master/packages/google_mobile_ads/example/ios/runner/nativeadview.xib
*/
@interface nativeadfactoryexample : nsobject <fltnativeadfactory>
@end

@implementation nativeadfactoryexample
- (gadnativeadview *)createnativead:(gadnativead *)nativead
                            customoptions:(nsdictionary *)customoptions {
 // create and place ad in view hierarchy.
 gadnativeadview *adview =
     [[nsbundle mainbundle] loadnibnamed:@"nativeadview" owner:nil options:nil].firstobject;

 // associate the native ad view with the native ad object. this is
 // required to make the ad clickable.
 adview.nativead = nativead;

 // populate the native ad view with the native ad assets.
 // the headline is guaranteed to be present in every native ad.
 ((uilabel *)adview.headlineview).text = nativead.headline;

 // these assets are not guaranteed to be present. check that they are before
 // showing or hiding them.
 ((uilabel *)adview.bodyview).text = nativead.body;
 adview.bodyview.hidden = nativead.body ? no : yes;

 [((uibutton *)adview.calltoactionview) settitle:nativead.calltoaction
                                        forstate:uicontrolstatenormal];
 adview.calltoactionview.hidden = nativead.calltoaction ? no : yes;

 ((uiimageview *)adview.iconview).image = nativead.icon.image;
 adview.iconview.hidden = nativead.icon ? no : yes;

 ((uilabel *)adview.storeview).text = nativead.store;
 adview.storeview.hidden = nativead.store ? no : yes;

 ((uilabel *)adview.priceview).text = nativead.price;
 adview.priceview.hidden = nativead.price ? no : yes;

 ((uilabel *)adview.advertiserview).text = nativead.advertiser;
 adview.advertiserview.hidden = nativead.advertiser ? no : yes;

 // in order for the sdk to process touch events properly, user interaction
 // should be disabled.
 adview.calltoactionview.userinteractionenabled = no;

 return adview;
}
@end

always test with test ads

when building and testing your apps, make sure you use test ads rather than live, production ads. failure to do so can lead to suspension of your account.

the easiest way to load test ads is to use our dedicated test ad unit id for native ads:

it’s been specially configured to return test ads for every request, and you’re free to use it in your own apps while coding, testing, and debugging. just make sure you replace it with your own ad unit id before publishing your app.

instantiate a native ad

a nativead requires an adunitid, a factoryid, an adrequest, and a nativeadlistener. an example is shown below as well as more information on each parameter following.

final nativead mynative = nativead(
  adunitid: '<test id or account id>',
  factoryid: 'adfactoryexample',
  request: adrequest(),
  listener: nativeadlistener(),
);

factory id

the factoryid will need to match the one used to add the factory to googlemobileadsplugin on android and/or the fltgooglemobileadsplugin on ios. the same factoryid can be used by both platforms or each can have their own.

native ad events

through the use of nativeadlistener, you can listen for lifecycle events, such as when an ad is closed or the user leaves the app. this example implements each method and logs a message to the console:

final nativeadlistener listener = nativeadlistener(
 // called when an ad is successfully received.
 onadloaded: (ad ad) => print('ad loaded.'),
 // called when an ad request failed.
 onadfailedtoload: (ad ad, loadaderror error) {
   // dispose the ad here to free resources.
   ad.dispose();
   print('ad failed to load: $error');
 },
 // called when an ad opens an overlay that covers the screen.
 onadopened: (ad ad) => print('ad opened.'),
 // called when an ad removes an overlay that covers the screen.
 onadclosed: (ad ad) => print('ad closed.'),
 // called when an impression occurs on the ad.
 onadimpression: (ad ad) => print('ad impression.'),
 // called when a click is recorded for a nativead.
 onnativeadclicked: (nativead ad) => print('ad clicked.'),
);

nativeadoptions

nativeads have an optional argument, nativeadoptions, which can be used to set specific options on the native ad.

shouldreturnurlsforimageassets

if set to `true`, the sdk will not load image asset content and native ad
image urls can be used to fetch content. defaults to false.

shouldrequestmultipleimages

some image assets will contain a series of images rather than just one. by setting this value to true,
your app indicates that it’s prepared to display all the images for any assets that have more than one.
by setting it to false (the default) your app instructs the sdk to provide just the first image for any assets that contain a series.

if no nativeadoptions are passed in when initializing a nativead, the default value for each property will be used.

adchoicesplacement

the [adchoices overlay](https://developers.google.com/admob/android/native/advanced#adchoices_overlay) is set to the top right corner by default.
apps can change which corner this overlay is rendered in by setting this property to one of the following:

  • adchoicesplacement.toprightcorner
  • adchoicesplacement.topleftcorner
  • adchoicesplacement.bottomrightcorner
  • adchoicesplacement.bottomleftcorner

videooptions

can be used to set video options for video assets returned as part of a native ad.

mediaaspectratio

this sets the aspect ratio for image or video to be returned for the native ad.
setting nativemediaaspectratio to one of the following constants will cause only ads with media of the specified aspect ratio to be returned:

  • mediaaspectratio.landscape
  • mediaaspectratio.portrait
  • mediaaspectratio.square
  • mediaaspectratio.any

if not set, ads with any aspect ratio will be returned.

load native ad

after a nativead is instantiated, load() must be called before it can be shown on the screen.

mynative.load();

display a native ad

to display a nativead as a widget, you must instantiate an adwidget with a supported ad after calling load(). you can create the widget before calling load(), but load() must be called before adding it to the widget tree.

final adwidget adwidget = adwidget(ad: mybanner);

adwidget inherits from flutter’s widget class and can be used as any other widget. on ios, make sure you place the widget in a widget with a specified width and height. otherwise, your ad may not be displayed.

final container adcontainer = container(
  alignment: alignment.center,
  child: adwidget,
  width: 500,
  height: 500,
);

once an ad has called load(), it must call dispose() when access to it is no longer needed. the best practice for when to call dispose() is either after the adwidget is removed from the widget tree or in the adlistener.onadfailedtoload callback.

that’s it! your app is now ready to display native ads.

next steps

rewarded ads

rewarded ads are ads that users have the option of interacting with in exchange for in-app rewards. this guide shows you how to integrate rewarded ads from admob into a flutter app.

always test with test ads

when building and testing your apps, make sure you use test ads rather than live, production ads. failure to do so can lead to suspension of your account.

the easiest way to load test ads is to use our dedicated test ad unit id for rewarded:

it’s been specially configured to return test ads for every request, and you’re free to use it in your own apps while coding, testing, and debugging. just make sure you replace it with your own ad unit id before publishing your app.

load a rewarded ad

loading a rewardedad requires an adunitid, an adrequest, and a rewardedadloadcallback. an example is shown below as well as more information on each parameter following.

rewardedad.load(
  adunitid: '<test id or account id>',
  request: adrequest(),
  rewardedadloadcallback: rewardedadloadcallback(
    onadloaded: (rewardedad ad) {
      print('$ad loaded.');
      // keep a reference to the ad so you can show it later.
      this._rewardedad = ad;
    },
    onadfailedtoload: (loadaderror error) {
      print('rewardedad failed to load: $error');
    },
);

rewarded ad events

through the use of fullscreencontentcallback, you can listen for lifecycle events, such as when the ad is shown or dismissed.
set rewardedad.fullscreencontentcallback before showing the ad to receive notifications for these events. this example implements each method and logs a message to the console:

rewardedad.fullscreencontentcallback = fullscreencontentcallback(
  onadshowedfullscreencontent: (rewardedad ad) =>
     print('$ad onadshowedfullscreencontent.'),
  onaddismissedfullscreencontent: (rewardedad ad) {
    print('$ad onaddismissedfullscreencontent.');
    ad.dispose();
  },
  onadfailedtoshowfullscreencontent: (rewardedad ad, aderror error) {
    print('$ad onadfailedtoshowfullscreencontent: $error');
    ad.dispose();
  },
  onadimpression: (rewardedad ad) => print('$ad impression occurred.'),
);

display a rewardedad

a rewardedad is displayed as an overlay is displayed on top of all app content and is statically placed. which means it can not be displayed this way can’t be added to the flutter widget tree. you can choose when to show the ad by calling show().
rewardedad.show() takes an onuserearnedrewardcallback, which is invoked when the user earns a reward. be sure to implement this and reward the user for watching an ad.

myrewarded.show(onuserearnedreward: (rewardedad ad, rewarditem rewarditem) {
  // reward the user for watching an ad.
});

once show() is called, an ad displayed this way can’t be removed programmatically and require user input. an rewardedad can only be shown once. subsequent calls to show will trigger onadfailedtoshowfullscreencontent.

once an ad has called load(), it must call dispose() when access to it is no longer needed. the best practice for when to call dispose() is in the fullscreencontentcallback.onaddismissedfullscreencontent and fullscreencontentcallback.onadfailedtoshowfullscreencontent callbacks.

that’s it! your app is now ready to display rewarded ads.

creating and loading an ad with ad manager

this section shows how to create and load ads with google ad manager.

select an ad format

  • banner
    • rectangular ads that appear at the top or bottom of the device screen. banner ads stay on screen while users are interacting with the app, and can refresh automatically after a certain period of time. if you’re new to mobile advertising, they’re a great place to start.
  • interstitial
    • full-screen ads that cover the interface of an app until closed by the user. they’re best used at natural pauses in the flow of an app’s execution, such as between levels of a game or just after a task is completed.
  • native ads
    • customizable ads that match the look and feel of your app. you decide how and where they’re placed, so the layout is more consistent with your app’s design.
  • rewarded
    • ads that reward users for watching short videos and interacting with playable ads and surveys. good for monetizing free-to-play users.

admanageradrequest

for ad manager you will be using admanageradrequest instead of adrequest.
admanageradrequest is similar to adrequest but has two additional properties: customtargeting and customtargetinglists,
which are used to support custom targeting.

final admanageradrequest request = admanageradrequest(
  keywords: <string>['flutterio', 'beautiful apps'],
  contenturl: 'https://flutter.dev',
  customtargeting: <string, string>{'some': 'targeting'},
  customtargetinglists: <string, list<string>>{'favoritecolors': <string>['red', 'yellow']},
);

ad manager banner ads

banner ads occupy a spot within an app’s layout, either at the top or bottom of the device screen. they stay on screen while users are interacting with the app, and can refresh automatically after a certain period of time.

this guide shows you how to integrate banner ads from ad manager into a flutter app. in addition to code snippets and instructions, it also includes information about sizing banners properly and links to additional resources.

see also the codelab for inline ads in flutter for a detailed guide on setting up banner ads.

always test with test ads

when building and testing your apps, make sure you use test ads rather than live, production ads. failure to do so can lead to suspension of your account.

the easiest way to load test ads is to use our dedicated test ad unit id for banners:

it’s been specially configured to return test ads for every request, and you’re free to use it in your own apps while coding, testing, and debugging. just make sure you replace it with your own ad unit id before publishing your app.

instantiate a banner ad

a admanagerbannerad requires an adunitid, an adsize, an adrequest, and an adlistener. an example is shown below as well as more information on each parameter following.

final admanagerbannerad mybanner = admanagerbannerad(
  adunitid: '<ad unit id>',
  size: adsize.banner,
  request: admanageradrequest(),
  listener: admanagerbanneradlistener(),
);

banner sizes

the table below lists the standard banner sizes.

size in dp (wxh) description adsize constant
320×50 standard banner banner
320×100 large banner largebanner
320×250 medium rectangle mediumrectangle
468×60 full-size banner fullbanner
728×90 leaderboard leaderboard
screen width x 32|50|90 smart banner use getsmartbanner(orientation)

to define a custom banner size, set your desired adsize, as shown here:

final adsize adsize = adsize(300, 50);

banner ad events

through the use of admanagerbanneradlistener, you can listen for lifecycle events, such as when an ad is closed. this example implements each method and logs a message to the console:

final admanagerbanneradlistener listener = admanagerbanneradlistener(
 // called when an ad is successfully received.
 onadloaded: (ad ad) => print('ad loaded.'),
 // called when an ad request failed.
 onadfailedtoload: (ad ad, loadaderror error) {
   // dispose the ad here to free resources.
   ad.dispose();
   print('ad failed to load: $error');
 },
 // called when an ad opens an overlay that covers the screen.
 onadopened: (ad ad) => print('ad opened.'),
 // called when an ad removes an overlay that covers the screen.
 onadclosed: (ad ad) => print('ad closed.'),
 // called when an impression occurs on the ad.
 onadimpression: (ad ad) => print('ad impression.'),
);

load banner ad

after a admanagerbannerad is instantiated, load() must be called before it can be shown on the screen.

mybanner.load();

display a banner ad

to display a admanagerbannerad as a widget, you must instantiate an adwidget with a supported ad after calling load(). you can create the widget before calling load(), but load() must be called before adding it to the widget tree.

final adwidget adwidget = adwidget(ad: mybanner);

adwidget inherits from flutter’s widget class and can be used as any other widget. on ios, make sure you place the widget in a widget with a specified width and height. otherwise, your ad may not be displayed. a admanagerbannerad can be placed in a container with a size that matches the ad:

final container adcontainer = container(
  alignment: alignment.center,
  child: adwidget,
  width: mybanner.size.width.todouble(),
  height: mybanner.size.height.todouble(),
);

once an ad has called load(), it must call dispose() when access to it is no longer needed. the best practice for when to call dispose() is either after the adwidget is removed from the widget tree or in the admanagerbanneradlistener.onadfailedtoload callback.

that’s it! your app is now ready to display banner ads.

ad manager interstitial ad

interstitial ads are full-screen ads that cover the interface of their host app. they’re typically displayed at natural transition points in the flow of an app, such as between activities or during the pause between levels in a game. when an app shows an interstitial ad, the user has the choice to either tap on the ad and continue to its destination or close it and return to the app.

this guide explains how to integrate interstitial ads into a flutter app.

always test with test ads

when building and testing your apps, make sure you use test ads rather than live, production ads. failure to do so can lead to suspension of your account.

the easiest way to load test ads is to use our dedicated test ad unit id for interstitials:

it’s been specially configured to return test ads for every request, and you’re free to use it in your own apps while coding, testing, and debugging. just make sure you replace it with your own ad unit id before publishing your app.

load an interstitial ad

loading an admanagerinterstitialad requires an adunitid, an adrequest, and an admanagerinterstitialadloadcallback. an example is shown below as well as more information on each parameter following.

admanagerinterstitialad.load(
  adunitid: '<ad unit id>',
  request: adrequest(),
  adloadcallback: admanagerinterstitialadloadcallback(
    onadloaded: (admanagerinterstitialad ad) {
      // keep a reference to the ad so you can show it later.
      this._interstitialad = ad;
    },
    onadfailedtoload: (loadaderror error) {
      print('interstitialad failed to load: $error');
    },
  ));

interstitial ad events

through the use of fullscreencontentcallback, you can listen for lifecycle events, such as when the ad is shown or dismissed.
set admanagerinterstitialad.fullscreencontentcallback before showing the ad to receive notifications for these events. this example implements each method and logs a message to the console:

interstitialad.fullscreencontentcallback = fullscreencontentcallback(
  onadshowedfullscreencontent: (interstitialad ad) =>
     print('$ad onadshowedfullscreencontent.'),
  onaddismissedfullscreencontent: (interstitialad ad) {
    print('$ad onaddismissedfullscreencontent.');
    ad.dispose();
  },
  onadfailedtoshowfullscreencontent: (interstitialad ad, aderror error) {
    print('$ad onadfailedtoshowfullscreencontent: $error');
    ad.dispose();
  },
  onadimpression: (interstitialad ad) => print('$ad impression occurred.'),
);

display an interstitial ad

a admanagerinterstitialad is displayed as an overlay on top of all app content and is statically placed. which means it can not be added to the flutter widget tree. you can choose when to show the ad by calling show().

myinterstitial.show();

once show() is called, an ad displayed this way can’t be removed programmatically and requires user input. an interstitialad can only be shown once. subsequent calls to show will trigger onadfailedtoshowfullscreencontent.

once an ad has called load(), it must call dispose() when access to it is no longer needed. the best practice for when to call dispose() is in the fullscreencontentcallback.onaddismissedfullscreencontent and fullscreencontentcallback.onadfailedtoshowfullscreencontent callbacks.

that’s it! your app is now ready to display interstitial ads.

next steps

ad manager native ads

native ads are ad assets that are presented to users via ui components that are native to the platform. they’re shown using the same types of views with which you’re already building your layouts, and can be formatted to match the visual design of the user experience in which they live. in coding terms, this means that when a native ad loads, your app receives a nativead object that contains its assets, and the app (rather than the google mobile ads sdk) is then responsible for displaying them.

broadly speaking, there are two parts to successfully implementing native ads: loading an ad via the sdk and displaying the ad content in your app. this guide is concerned with using the sdk to load native ads.

see also the codelab for inline ads in flutter for a detailed guide on setting up native ads.

platform setup

native ads are presented to users via ui components that are native to the platform. (e.g. a view on android or a uiview on ios).

since native ads require ui components native to a platform, this feature requires additional setup for android and ios:

android

the android implementation of the google mobile ads plugin requires a class that implements a nativeadfactory. a nativeadfactory contains a method that takes a nativead and custom options and returns a nativeadview. the nativeadview is what will be displayed in your app.

you can implement this in your mainactivity.java or create a separate class in the same directory as mainactivity.java as seen below:

package my.app.path;

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;

class nativeadfactoryexample implements nativeadfactory {
  @override
  public nativeadview createnativead(
      nativead nativead, map<string, object> customoptions) {
    // create nativeadview
  }
}

each nativeadfactory needs to be registered with a factoryid, a unique string identifier, in mainactivity.configureflutterengine(flutterengine). a nativeadfactory can be implemented and registered for each unique native ad layout used by your app or a single one can handle all layouts. the nativeadfactory should also be unregistered in cleanupflutterengine(engine) when building with add-to-app.

mainactivity.java should look similar to:

package my.app.path;

import io.flutter.embedding.android.flutteractivity;
import io.flutter.embedding.engine.flutterengine;
import io.flutter.plugins.googlemobileads.googlemobileadsplugin;

public class mainactivity extends flutteractivity {
  @override
  public void configureflutterengine(flutterengine flutterengine) {
    flutterengine.getplugins().add(new googlemobileadsplugin());
   super.configureflutterengine(flutterengine);

    googlemobileadsplugin.registernativeadfactory(flutterengine, "adfactoryexample", nativeadfactoryexample());
  }

  @override
  public void cleanupflutterengine(flutterengine flutterengine) {
    googlemobileadsplugin.unregisternativeadfactory(flutterengine, "adfactoryexample");
  }
}

when creating the nativead in dart, the factoryid will need to match the one used to add the factory to googlemobileadsplugin. in the above code snippet, adfactoryexample is the name of the factoryid. an example nativeadfactory follows:

package io.flutter.plugins.googlemobileadsexample;

import android.graphics.color;
import android.view.layoutinflater;
import android.widget.textview;
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
/* https://github.com/googleads/googleads-mobile-flutter/tree/master/packages/google_mobile_ads/example/android/app/src/main/res/layout
*/
class nativeadfactoryexample implements nativeadfactory {
 private final layoutinflater layoutinflater;

 nativeadfactoryexample(layoutinflater layoutinflater) {
   this.layoutinflater = layoutinflater;
 }

 @override
 public nativeadview createnativead(
     nativead nativead, map<string, object> customoptions) {
   final nativeadview adview =
       (nativeadview) layoutinflater.inflate(r.layout.my_native_ad, null);
   final textview headlineview = adview.findviewbyid(r.id.ad_headline);
   final textview bodyview = adview.findviewbyid(r.id.ad_body);

   headlineview.settext(nativead.getheadline());
   bodyview.settext(nativead.getbody());

   adview.setbackgroundcolor(color.yellow);

   adview.setnativead(nativead);
   adview.setbodyview(bodyview);
   adview.setheadlineview(headlineview);
   return adview;
 }
}

ios

the ios implementation of the google mobile ads plugin requires a class that implements a fltnativeadfactory. a fltnativeadfactory contains a method that takes a gadnativead and custom options and returns a gadnativeadview. the gadnativeadview is what will be displayed in your app.

the fltnativeadfactory protocol can be implemented by appdelegate or a separate class could be created as seen below:

/* appdelegate.m */
#import "fltgooglemobileadsplugin.h"
@interface nativeadfactoryexample : nsobject<fltnativeadfactory>
@end

@implementation nativeadfactoryexample
- (gadnativeadview *)createnativead:(gadnativead *)nativead
                             customoptions:(nsdictionary *)customoptions {
  // create gadnativeadview
}
@end

each fltnativeadfactory needs to be registered with a factoryid, a unique string identifier, in registernativeadfactory:factoryid:nativeadfactory:. a fltnativeadfactory can be implemented and registered for each unique native ad layout used by your app or a single one can handle all layouts. this is done by importing fltgooglemobileadsplugin.h and calling registernativeadfactory:factoryid:nativeadfactory: with a flutterpluginregistry, a unique identifier for the factory, and the factory itself. the factory also must be added after [generatedpluginregistrant registerwithregistry:self]; has been called.

if this is done in appdelegate.m, it should look similar to:

#import "fltgooglemobileadsplugin.h"

@implementation appdelegate
- (bool)application:(uiapplication *)application
    didfinishlaunchingwithoptions:(nsdictionary *)launchoptions {
  [generatedpluginregistrant registerwithregistry:self];

  nativeadfactoryexample *nativeadfactory = [[nativeadfactoryexample alloc] init];
  [fltgooglemobileadsplugin registernativeadfactory:self
                                        factoryid:@"adfactoryexample"
                                  nativeadfactory:nativeadfactory];

  return [super application:application didfinishlaunchingwithoptions:launchoptions];
}
@end

when creating the nativead in dart, the factoryid will need to match the one used to add the factory to fltgooglemobileadsplugin. in the above code snippet, adfactoryexample is the name of the factoryid.an examplefltnativeadfactory` follows:

// the example nativeadview.xib can be found at
/* https://github.com/googleads/googleads-mobile-flutter/blob/master/packages/google_mobile_ads/example/ios/runner/nativeadview.xib
*/
@interface nativeadfactoryexample : nsobject <fltnativeadfactory>
@end

@implementation nativeadfactoryexample
- (gadnativeadview *)createnativead:(gadnativead *)nativead
                            customoptions:(nsdictionary *)customoptions {
 // create and place ad in view hierarchy.
 gadnativeadview *adview =
     [[nsbundle mainbundle] loadnibnamed:@"nativeadview" owner:nil options:nil].firstobject;

 // associate the native ad view with the native ad object. this is
 // required to make the ad clickable.
 adview.nativead = nativead;

 // populate the native ad view with the native ad assets.
 // the headline is guaranteed to be present in every native ad.
 ((uilabel *)adview.headlineview).text = nativead.headline;

 // these assets are not guaranteed to be present. check that they are before
 // showing or hiding them.
 ((uilabel *)adview.bodyview).text = nativead.body;
 adview.bodyview.hidden = nativead.body ? no : yes;

 [((uibutton *)adview.calltoactionview) settitle:nativead.calltoaction
                                        forstate:uicontrolstatenormal];
 adview.calltoactionview.hidden = nativead.calltoaction ? no : yes;

 ((uiimageview *)adview.iconview).image = nativead.icon.image;
 adview.iconview.hidden = nativead.icon ? no : yes;

 ((uilabel *)adview.storeview).text = nativead.store;
 adview.storeview.hidden = nativead.store ? no : yes;

 ((uilabel *)adview.priceview).text = nativead.price;
 adview.priceview.hidden = nativead.price ? no : yes;

 ((uilabel *)adview.advertiserview).text = nativead.advertiser;
 adview.advertiserview.hidden = nativead.advertiser ? no : yes;

 // in order for the sdk to process touch events properly, user interaction
 // should be disabled.
 adview.calltoactionview.userinteractionenabled = no;

 return adview;
}
@end

always test with test ads

when building and testing your apps, make sure you use test ads rather than live, production ads. failure to do so can lead to suspension of your account.

the easiest way to load test ads is to use our dedicated test ad unit id for native ads:

it’s been specially configured to return test ads for every request, and you’re free to use it in your own apps while coding, testing, and debugging. just make sure you replace it with your own ad unit id before publishing your app.

instantiate a native ad

a nativead requires an adunitid, a factoryid, an adrequest, and an adlistener. an example is shown below as well as more information on each parameter following.

final nativead mynative = nativead.fromadmanagerrequest(
  adunitid: '<test id or account id>',
  factoryid: 'adfactoryexample',
  admanagerrequest: admanageradrequest(),
  listener: nativeadlistener(),
);

factory id

the factoryid will need to match the one used to add the factory to googlemobileadsplugin on android and/or the fltgooglemobileadsplugin on ios. the same factoryid can be used by both platforms or each can have their own.

native ad events

through the use of nativeadlistener, you can listen for lifecycle events, such as when an ad is closed or the user leaves the app. this example implements each method and logs a message to the console:

final nativeadlistener listener = nativeadlistener(
 // called when an ad is successfully received.
 onadloaded: (ad ad) => print('ad loaded.'),
 // called when an ad request failed.
 onadfailedtoload: (ad ad, loadaderror error) {
   // dispose the ad here to free resources.
   ad.dispose();
   print('ad failed to load: $error');
 },
 // called when an ad opens an overlay that covers the screen.
 onadopened: (ad ad) => print('ad opened.'),
 // called when an ad removes an overlay that covers the screen.
 onadclosed: (ad ad) => print('ad closed.'),
 // called when an impression occurs on the ad.
 onadimpression: (ad ad) => print('ad impression.'),
 // called when a click is recorded for a nativead.
 onnativeadclicked: (nativead ad) => print('ad clicked.'),
);

nativeadoptions

nativeads have an optional argument, nativeadoptions, which can be used to set specific options on the native ad.

shouldreturnurlsforimageassets

if set to `true`, the sdk will not load image asset content and native ad
image urls can be used to fetch content. defaults to false.

shouldrequestmultipleimages

some image assets will contain a series of images rather than just one. by setting this value to true,
your app indicates that it’s prepared to display all the images for any assets that have more than one.
by setting it to false (the default) your app instructs the sdk to provide just the first image for any assets that contain a series.

if no nativeadoptions are passed in when initializing a nativead, the default value for each property will be used.

adchoicesplacement

the [adchoices overlay](https://developers.google.com/admob/android/native/advanced#adchoices_overlay) is set to the top right corner by default.
apps can change which corner this overlay is rendered in by setting this property to one of the following:

  • adchoicesplacement.toprightcorner
  • adchoicesplacement.topleftcorner
  • adchoicesplacement.bottomrightcorner
  • adchoicesplacement.bottomleftcorner

videooptions

can be used to set video options for video assets returned as part of a native ad.

mediaaspectratio

this sets the aspect ratio for image or video to be returned for the native ad.
setting nativemediaaspectratio to one of the following constants will cause only ads with media of the specified aspect ratio to be returned:

  • mediaaspectratio.landscape
  • mediaaspectratio.portrait
  • mediaaspectratio.square
  • mediaaspectratio.any

if not set, ads with any aspect ratio will be returned.

load native ad

after a nativead is instantiated, load() must be called before it can be shown on the screen.

mynative.load();

display a native ad

to display a nativead as a widget, you must instantiate an adwidget with a supported ad after calling load(). you can create the widget before calling load(), but load() must be called before adding it to the widget tree.

final adwidget adwidget = adwidget(ad: mybanner);

adwidget inherits from flutter’s widget class and can be used as any other widget. on ios, make sure you place the widget in a widget with a specified width and height. otherwise, your ad may not be displayed.

final container adcontainer = container(
  alignment: alignment.center,
  child: adwidget,
  width: 500,
  height: 500,
);

once an ad has called load(), it must call dispose() when access to it is no longer needed. the best practice for when to call dispose() is either after the adwidget is removed from the widget tree or in the adlistener.onadfailedtoload callback.

that’s it! your app is now ready to display native ads.

next steps

ad manager rewarded ads

rewarded ads are ads that users have the option of interacting with in exchange for in-app rewards. this guide shows you how to integrate rewarded ads from ad manager into a flutter app.

always test with test ads

when building and testing your apps, make sure you use test ads rather than live, production ads. failure to do so can lead to suspension of your account.

the easiest way to load test ads is to use our dedicated test ad unit id for rewarded:

it’s been specially configured to return test ads for every request, and you’re free to use it in your own apps while coding, testing, and debugging. just make sure you replace it with your own ad unit id before publishing your app.

load a rewarded ad

loading a rewardedad requires an adunitid, an admanageradrequest, and a rewardedadloadcallback. an example is shown below as well as more information on each parameter following.

rewardedad.loadwithadmanageradrequest(
  adunitid: '<test id or account id>',
  admanagerrequest: admanageradrequest(),
  rewardedadloadcallback: rewardedadloadcallback(
    onadloaded: (rewardedad ad) {
      print('$ad loaded.');
      // keep a reference to the ad so you can show it later.
      this._rewardedad = ad;
    },
    onadfailedtoload: (loadaderror error) {
      print('rewardedad failed to load: $error');
    },
);

rewarded ad events

through the use of fullscreencontentcallback, you can listen for lifecycle events, such as when the ad is shown or dismissed.
set rewardedad.fullscreencontentcallback before showing the ad to receive notifications for these events. this example implements each method and logs a message to the console:

rewardedad.fullscreencontentcallback = fullscreencontentcallback(
  onadshowedfullscreencontent: (rewardedad ad) =>
     print('$ad onadshowedfullscreencontent.'),
  onaddismissedfullscreencontent: (rewardedad ad) {
    print('$ad onaddismissedfullscreencontent.');
    ad.dispose();
  },
  onadfailedtoshowfullscreencontent: (rewardedad ad, aderror error) {
    print('$ad onadfailedtoshowfullscreencontent: $error');
    ad.dispose();
  },
  onadimpression: (rewardedad ad) => print('$ad impression occurred.'),
);

display a rewardedad

a rewardedad is displayed as an overlay is displayed on top of all app content and is statically placed. which means it can not be displayed this way can’t be added to the flutter widget tree. you can choose when to show the ad by calling show().
a rewardedad can only be shown once. subsequent calls to show will trigger onadfailedtoshowfullscreencontent.
rewardedad.show() takes an onuserearnedrewardcallback, which is invoked when the user earns a reward. be sure to implement this and reward the user for watching an ad.

myrewarded.show(onuserearnedreward: (rewardedad ad, rewarditem rewarditem) {
  // reward the user for watching an ad.
});

once show() is called, an ad displayed this way can’t be removed programmatically and require user input. do not call show() more than once for a loaded rewardedad. instead you should load a new ad.

once an ad has called load(), it must call dispose() when access to it is no longer needed. the best practice for when to call dispose() is in the fullscreencontentcallback.onaddismissedfullscreencontent and fullscreencontentcallback.onadfailedtoshowfullscreencontent callbacks.

that’s it! your app is now ready to display rewarded ads.

next steps

targeting

the requestconfiguration object collects the global configuration for every ad request and is applied bymobileads.instance.updaterequestconfiguration().

child-directed setting

for purposes of the children’s online privacy protection act (coppa), there is a setting called “tag for child-directed treatment.”

as an app developer, you can indicate whether you want google to treat your content as child-directed when you make an ad request. if you indicate that you want google to treat your content as child-directed, we take steps to disable iba and remarketing ads on that ad request. the setting can be used with all versions of the google play services sdk viarequestconfiguration.tagforchilddirectedtreatment():

  • use the argument tagforchilddirectedtreatment.yes to indicate that you want your content treated as child-directed for the purposes of coppa.
  • use the argument tagforchilddirectedtreatment.no to indicate that you don’t want your content treated as child-directed for the purposes of coppa.
  • use the argument tagforchilddirectedtreatment.unspecified or do not set this tag if you do not wish to indicate how you would like your content treated with respect to coppa in ad requests.

the following example indicates that you want your content treated as child-directed for purposes of coppa:

final requestconfiguration requestconfiguration = requestconfiguration(
  tagforchilddirectedtreatment: tagforchilddirectedtreatment.yes);
mobileads.instance.updaterequestconfiguration(requestconfiguration);

users under the age of consent

you can mark your ad requests to receive treatment for users in the european economic area (eea) under the age of consent. this feature is designed to help facilitate compliance with the general data protection regulation (gdpr). note that you may have other legal obligations under gdpr. please review the european union’s guidance and consult with your own legal counsel. please remember that google’s tools are designed to facilitate compliance and do not relieve any particular publisher of its obligations under the law. learn more about how the gdpr affects publishers.

when using this feature, a tag for users under the age of consent in europe (tfua) parameter will be included in the ad request. this parameter disables personalized advertising, including remarketing, for that specific ad request. it also disables requests to third-party ad vendors, such as ad measurement pixels and third-party ad servers.

the setting can be used via requestconfiguration.tagforunderageofconsent():

  • use the argument tagforunderageofconsent.yes to indicate that you want the request configuration to be handled in a manner suitable for users under the age of consent.
  • use the argument tagforunderageofconsent.no to indicates that you don’t want the request configuration to be handled in a manner suitable for users under the age of consent.
  • use the argument tagforunderageofconsent.unspecified or do not set this tag to indicate that you have not specified whether the ad request should receive treatment for users in the european economic area (eea) under the age of consent. the following example indicates that you want tfua included in your ad request:
final requestconfiguration requestconfiguration = requestconfiguration(
  tagforunderageofconsent: tagforunderageofconsent.yes);
mobileads.instance.updaterequestconfiguration(requestconfiguration);

the tags to enable the child-directed setting and settagforunderageofconsent should not both simultaneously be set to true. if they are, the child-directed setting takes precedence.

ad content filtering

the setting can be set viarequestconfiguration.maxadcontentrating():

admob ads returned for these requests have a content rating at or below that level. the possible values for this network extra are based on digital content label classifications, and should be one of the followingmaxadcontentrating objects:

  • maxadcontentrating.g
  • maxadcontentrating.pg
  • maxadcontentrating.t
  • maxadcontentrating.ma

the following code configures arequestconfiguration object to specify that ad content returned should correspond to a digital content label designation no higher than g:

final requestconfiguration requestconfiguration = requestconfiguration(
  maxadcontentrating: maxadcontentrating.g);
mobileads.instance.updaterequestconfiguration(requestconfiguration);

response info

for debugging and logging purposes, loadaderrors and successfully loaded ads
provide a responseinfo object. this object contains information about the ad
it loaded. each ad format class has a property ad.responseinfo which is
populated after it loads.

properties on the responseinfo object include:

mediationadapterclassname
: the class name of the ad network that fetched the current ad.

responseid
: the response identifier is a unique identifier for the ad response. this
identifier can be used to identify and block the ad in the ads review center
(arc).

adapterresponses
: the list of adapterresponseinfo containing metadata for each adapter
included in the ad response. can be used to debug the mediation waterfall
execution.

for each ad network in the waterfall, adapterresponseinfo provides the following
properties:

property description
adapterclassname a class name that identifies the ad network.
credentials a string description of adapter credentials specified in the admob or ad
manager ui.
aderror error associated with the request to the network. null if the network
successfully loaded an ad or if the network was not attempted.
latencymillis amount of time the ad network spent loading an ad. 0 if the
network was not attempted.
description a log friendly string version of the adapterresponseinfo.

ad load errors

when an ad fails to load, a failure callback is called which provides a
loadaderror object.

the following code snippet retrieves error information when a rewarded ad fails
to load:

onadfailedtoload: (ad, loadaderror) {
  // gets the domain from which the error came.
  string domain = loadaderror.domain;

  // gets the error code. see
  // https://developers.google.com/android/reference/com/google/android/gms/ads/adrequest
  // and https://developers.google.com/admob/ios/api/reference/enums/gaderrorcode
  // for a list of possible codes.
  int code = loadaderror.code;
  
  // a log friendly string summarizing the error.
  string message = loadaderror.message;
  
  // get response information, which may include results of mediation requests.
  responseinfo? responseinfo = loadaderror.responseinfo;
}

Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

Comments are closed.