Skip to content
This repository has been archived by the owner on Mar 12, 2022. It is now read-only.

Using the controller and listening to banner events

Bruno D'Luka edited this page Jan 18, 2021 · 2 revisions

To have better control over the ad, you can a BannerAdController:

Initialize the controller

// Init the controller
final controller = BannerAdController();

// Use the controller in the BannerAd
@override
Widget build(BuildContext context) {
  return BannerAd(controller: controller);
}

// Dispose the controller to free up resources. 
// You can't use the it again once it's disposed
@override
void dispose() {
  controller.dispose();
  super.dispose();
}

(Re)loading the ad

To load or reload the ad, use controller.load():

controller.load()

If your ad fails to load, you don't need to explicitly request another one as long as you've configured your ad unit to refresh; the Google Mobile Ads SDK respects any refresh rate you specified in the AdMob UI. If you haven't enabled refresh, you will need to issue a new request.

Listening to events

You can listen to the events the ad throws using controller.onEvent:

@override
void initState() {
  super.initState();
  controller.onEvent.listen((e) {
      final event = e.keys.first;
      switch (event) {
        case BannerAdEvent.loading:
          print('loading');
          break;
        case BannerAdEvent.loaded:
          print('loaded');
          break;
        case BannerAdEvent.loadFailed:
          final errorCode = e.values.first;
          print('loadFailed $errorCode');
          break;
        case BannerAdEvent.impression:
          print('ad rendered');
          break;
        case BannerAdEvent.clicked;
          print('clicked');
          break;
        default:
          break;
      }
  });
}