ads 1.0.1

Add Ads to your App in a Snap! #

This Dart package will utilize the plugin, firebase_admob, so to quickly and easily implement ads into a Flutter app.

Sign Up and Get Your ID’s #

First and foremost, you have to sign up for AdMob. Please, turn to AdMob Help for further guidance on this. You’re going to have to go to your Google AdMob Dashboard and get your id’s as well. There’s the ‘app ID’ used to identify your individual app, and there’s individual unit ID’s unique to each ‘type’ of ad you decide to use. Currently, there are three types: a Banner ad, an Interstitial ad, and a Video ad. Might as well do all that now, and then come back here to learn how to display such ads in your Flutter app. GoogleAdMob

It’s A Test. Not For Real #

Note, test id’s are supplied by the plugin to be used during development. Using your own id would violate ‘AdMob by Google’ policy. You can’t be clicking ads on your own app. They’ll know.

For Android, Modify AndroidManifest.xml #

A common error you may encounter when trying this package out is Google complaining that the AdMob was not properly initialized. Merely follow the directions below to resolve this: androidManifest

For iOS, Update your Info.plist #

Info.plist and add Info plist

Your App's Analytics in Ads #

So, you created an AdMob account in order to monetize with ads in your production app. However, the kind of ads displayed will get a little help if you assign a Firebase project to your app as well. In fact, it's been suggested to be an esstential step, Missing setup steps in readme. This is yet to be confirmed however. Regardless, turn to the links below to add Firebase to your app: Add Firebase to your iOS project and Add Firebase to your Android project FirebaseToiOS FirebaseToAndroid

failed to load ad : 3 #

errorLoadAd03 Patience is a virtue. The only errors I consistently receive from users are not of the Dart package itself, but are due to Google. Once the user has registered with Google, a common complaint is there’s still only ‘test’ ads being displayed, but that’s because it’ll take some hours if not a day to receive production ads. Wait a day, and see for yourself.

Install Ads as a Package #

Dart uses packages to distribute libraries like this one. You can find publicly available packages on the Pub site. The Ads package in particular. ads

There Must Only Be One! #

Try instantiating more than one Ads object, and you'll be a little dissappointed if not down right confused. It'll appear the second Ads object is not working, and you'd be right.

    _ads = Ads(
      appId,
      bannerUnitId: bannerUnitId,
      screenUnitId: screenUnitId,
      keywords: <String>['ibm', 'computers'],
      contentUrl: 'http://www.ibm.com',
      childDirected: false,
      testDevices: ['Samsung_Galaxy_SII_API_26:5554'],
      listener: eventListener,
    );

    _adsTest = Ads(
      appId,
      bannerUnitId: bannerUnitId,
      screenUnitId: screenUnitId,
      keywords: <String>['ibm', 'computers'],
      contentUrl: 'http://www.ibm.com',
      childDirected: false,
      testDevices: ['Samsung_Galaxy_SII_API_26:5554'],
      listener: eventListener,
    );

The Google plugin is designed to work with one app and its set of ads. That's all. Creating another Ads object will serve no purpose for you because the Ads Dart package will be aware of the first one and work only with that one. Note, they'll be no 'error message' or notification there's more than one Ads object. The Dart package is designed not to be that disruptive in development or in production. The second object will just not do anything. It simply won't work, and will record the reason why in the log files. That's all.

Keep It Static #

A means to have access to the Ads instance from 'anywhere' in our app would be to have it all contained in a static ulitity class. Below only the showBannerAd() and dispose() functions are implemented, but you'll get the idea and should able to implement any and all the functions you require:

AppAds.dart #

class AppAds {
  static Ads _ads;

  static final String _appId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544~3347511713'
      : 'ca-app-pub-3940256099942544~1458002511';

  static final String _bannerUnitId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544/6300978111'
      : 'ca-app-pub-3940256099942544/2934735716';

  /// Assign a listener.
  static AdEventListener _eventListener = (MobileAdEvent event) {
    if (event == MobileAdEvent.clicked) {
      print("The opened ad is clicked on.");
    }
  };

  static void showBanner(
          {String adUnitId,
          AdSize size,
          List<String> keywords,
          String contentUrl,
          bool childDirected,
          List<String> testDevices,
          bool testing,
          AdEventListener listener,
          State state,
          double anchorOffset,
          AnchorType anchorType}) =>
      _ads?.showBannerAd(
          adUnitId: adUnitId,
          size: size,
          keywords: keywords,
          contentUrl: contentUrl,
          childDirected: childDirected,
          testDevices: testDevices,
          testing: testing,
          listener: listener,
          state: state,
          anchorOffset: anchorOffset,
          anchorType: anchorType);

  static void hideBanner() => _ads?.hideBannerAd();

  /// Call this static function in your State object's initState() function.
  static void init() => _ads ??= Ads(
        _appId,
        bannerUnitId: _bannerUnitId,
        keywords: <String>['ibm', 'computers'],
        contentUrl: 'http://www.ibm.com',
        childDirected: false,
        testDevices: ['Samsung_Galaxy_SII_API_26:5554'],
        testing: false,
        listener: _eventListener,
      );

  /// Remember to call this in the State object's dispose() function.
  static void dispose() => _ads?.dispose();
}

Simply import the Dart file, AppAds.dart, in this case to any library file you would need access to the Ads for one reason or another, and you're on your way.

There's An Article On This #

There is an extensive article about this Dart package available on medium.com: Add Ads To Your App in a Snap!

admobFlutter03

How it works #

appCodeSample gist: AdMobAdsExample.dart

import 'package:flutter/material.dart';
import 'dart:io' show Platform;
import 'package:firebase_admob/firebase_admob.dart';

import 'package:ads/ads.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Ads appAds;
  int _coins = 0;

  final String appId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544~3347511713'
      : 'ca-app-pub-3940256099942544~1458002511';

  final String bannerUnitId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544/6300978111'
      : 'ca-app-pub-3940256099942544/2934735716';

  final String screenUnitId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544/1033173712'
      : 'ca-app-pub-3940256099942544/4411468910';

  final String videoUnitId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544/5224354917'
      : 'ca-app-pub-3940256099942544/1712485313';

  @override
  void initState() {
    super.initState();

    /// Assign a listener.
    var eventListener = (MobileAdEvent event) {
      if (event == MobileAdEvent.opened) {
        print("The opened ad is clicked on.");
      }
    };

    appAds = Ads(
      appId,
      bannerUnitId: bannerUnitId,
      screenUnitId: screenUnitId,
      keywords: <String>['ibm', 'computers'],
      contentUrl: 'http://www.ibm.com',
      childDirected: false,
      testDevices: ['Samsung_Galaxy_SII_API_26:5554'],
      testing: false,
      listener: eventListener,
    );

    appAds.setVideoAd(
      adUnitId: videoUnitId,
      keywords: ['dart', 'java'],
      contentUrl: 'http://www.publang.org',
      childDirected: true,
      testDevices: null,
      listener: (RewardedVideoAdEvent event,
          {String rewardType, int rewardAmount}) {
        print("The ad was sent a reward amount.");
        setState(() {
          _coins += rewardAmount;
        });
      },
    );

    appAds.showBannerAd();
  }

  @override
  void dispose() {
    appAds.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('AdMob Ad Examples'),
        ),
        body: SingleChildScrollView(
          child: Center(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                RaisedButton(
                    key: ValueKey<String>('SHOW BANNER'),
                    child: const Text('SHOW BANNER'),
                    onPressed: () {
                      appAds.showBannerAd(state: this, anchorOffset: null);
                    }),
                RaisedButton(
                    key: ValueKey<String>('REMOVE BANNER'),
                    child: const Text('REMOVE BANNER'),
                    onPressed: () {
                      appAds.hideBannerAd();
                    }),
                RaisedButton(
                  key: ValueKey<String>('SHOW INTERSTITIAL'),
                  child: const Text('SHOW INTERSTITIAL'),
                  onPressed: () {
                    appAds.showFullScreenAd(state: this);
                  },
                ),
                RaisedButton(
                  key: ValueKey<String>('SHOW REWARDED VIDEO'),
                  child: const Text('SHOW REWARDED VIDEO'),
                  onPressed: () {
                    appAds.showVideoAd(state: this);
                  },
                ),
                Text(
                  "You have $_coins coins.",
                  key: ValueKey<String>('COINS'),
                ),
              ].map((Widget button) {
                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 16.0),
                  child: button,
                );
              }).toList(),
            ),
          ),
        ),
      ),
    );
  }
}

Beta You Bet! #

As of this writing, firebase_admob, is still in beta. As such, Banner ads can only be positioned at the top or the bottom of the screen, animation is limited, the ads come in a infinite set of sizes. Lastly, 'native ads' (i.e. ads displayed on UI components native to the platform) are not yet supported.

And the Number of the Counting Shall Be…Three #

There are three types of ads currently offered by the firebase_admob plugin. There's the traditional Banner ad, the Interstitial or full-screen ad that covers the interface of their host app when opened, and finally, there's the Video ad that also covers the screen when opened and then returns to the app when closed.

Three types of ads.

It's an Event! #

The plugin, firebase_admob, watches for seven separate events when it comes to the Banner ad and the Full-screen ad. Everything from the much-called 'loaded' event to the 'impression' event---which I think fires each if the user has been looking at the ad for so long that the ad itself has refreshed itself. I'm not certain however as there's not much API documentation for this plugin at the time of this writing either.

Below is the the enumerated values currently describing the currently supported events:

Seven events are available to the Banner and Full-screen ad.

With Video ads, there are eight events made available to watch out for. Events are triggered, for example, when the video opens, when the video starts to play, and when the video has completed running. There's also an event that rewards the user for viewing the video.

Eight events associated with a Video.

Listen and Earn! #

Since the plugin supplies a whole bunch of events, I've implemented no less than eleven event listeners in this library. The gist provided above lists all the possibles ways to set an event handler on all the types of ads offered by the plugin.

The Banner ad and the FullScreen ad use the same set of 'MobileAdEvent' events while the Video Ad has its own set under the event type, 'RewardedVideoAdEvent'. This means you can break up your event listeners by the type of ad if you want.

Yes, you can assign as many listeners as you want to a particular event. You or someone else can. For example, someone else on your team working on another part of your app may also need to know when an ad is opened.

The Main Event Listener #

There is a setter called, eventListener, that you can use to catch 'MobileAdEvent' events. Again, currently there is seven events defined so far and are used by the Banner ad and the Full-Screen (Interstitial) ad.

  appAds.eventListener = (MobileAdEvent event) {
    switch (event) {
      case MobileAdEvent.loaded:
        print("An ad has loaded successfully in memory.");
        break;
      case MobileAdEvent.failedToLoad:
        print("The ad failed to load into memory.");
        break;
      case MobileAdEvent.clicked:
        print("The opened ad was clicked on.");
        break;
      case MobileAdEvent.impression:
        print("The user is still looking at the ad. A new ad came up.");
        break;
      case MobileAdEvent.opened:
        print("The Ad is now open.");
        break;
      case MobileAdEvent.leftApplication:
        print("You've left the app after clicking the Ad.");
        break;
      case MobileAdEvent.closed:
        print("You've closed the Ad and returned to the app.");
        break;
      default:
        print("There's a 'new' MobileAdEvent?!");
    }
  };

Again, you can assign a listener at the init() function and at the 'set' functions---any number of listeners you like. There's functions available to remove these listeners as well of course.

The Banner Listener #

The Banner ad has its own setter. You can see below it's called bannerListener.

  appAds.bannerListener = (MobileAdEvent event) {
    switch (event) {
      case MobileAdEvent.loaded:
        print("An ad has loaded successfully in memory.");
        break;
      case MobileAdEvent.failedToLoad:
        print("The ad failed to load into memory.");
        break;
      case MobileAdEvent.clicked:
        print("The opened ad was clicked on.");
        break;
      case MobileAdEvent.impression:
        print("The user is still looking at the ad. A new ad came up.");
        break;
      case MobileAdEvent.opened:
        print("The ad is now open.");
        break;
      case MobileAdEvent.leftApplication:
        print("You've left the app after clicking the Ad.");
        break;
      case MobileAdEvent.closed:
        print("You've closed the Ad and returned to the app.");
        break;
      default:
        print("There's a 'new' MobileAdEvent?!");
    }
  };

The Full-Screen Listener #

The setter for the Interstitial ad is called screenListener.

  appAds.screenListener = (MobileAdEvent event) {
    switch (event) {
      case MobileAdEvent.loaded:
        print("An ad has loaded successfully in memory.");
        break;
      case MobileAdEvent.failedToLoad:
        print("The ad failed to load into memory.");
        break;
      case MobileAdEvent.clicked:
        print("The opened ad was clicked on.");
        break;
      case MobileAdEvent.impression:
        print("The user is still looking at the ad. A new ad came up.");
        break;
      case MobileAdEvent.opened:
        print("The ad is now open.");
        break;
      case MobileAdEvent.leftApplication:
        print("You've left the app after clicking the Ad.");
        break;
      case MobileAdEvent.closed:
        print("You've closed the Ad and returned to the app.");
        break;
      default:
        print("There's a 'new' MobileAdEvent?!");
    }
  };

The Video Listener #

Finally, the setter for the Video ad is called videoListener.

  appAds.videoListener =
      (RewardedVideoAdEvent event, {String rewardType, int rewardAmount}) {
    switch (event) {
      case RewardedVideoAdEvent.loaded:
        print("An ad has loaded successfully in memory.");
        break;
      case RewardedVideoAdEvent.failedToLoad:
        print("The ad failed to load into memory.");
        break;
      case RewardedVideoAdEvent.opened:
        print("The ad is now open.");
        break;
      case RewardedVideoAdEvent.leftApplication:
        print("You've left the app after clicking the Ad.");
        break;
      case RewardedVideoAdEvent.closed:
        print("You've closed the Ad and returned to the app.");
        break;
      case RewardedVideoAdEvent.rewarded:
        print("The ad has sent a reward amount.");
        break;
      case RewardedVideoAdEvent.started:
        print("You've just started playing the Video ad.");
        break;
      case RewardedVideoAdEvent.completed:
        print("You've just finished playing the Video ad.");
        break;
      default:
        print("There's a 'new' RewardedVideoAdEvent?!");
    }
  };

A Event Listener For Every Occasion #

This last section provides yet another way to implement a specific event listeners for your ads:

  appAds.banner.loadedListener = () {
    print("An ad has loaded successfully in memory.");
  };

  appAds.banner.failedListener = () {
    print("An ad failed to load into memory.");
  };

  appAds.banner.clickedListener = () {
    print("The opened ad is clicked on.");
  };

  appAds.banner.impressionListener = () {
    print("The user is still looking at the ad. A new ad came up.");
  };

  appAds.banner.openedListener = () {
    print("The ad has opened.");
  };

  appAds.banner.leftAppListener = () {
    print("You left the app and gone to the ad's website.");
  };

  appAds.banner.impressionListener = () {
    print("The user is still looking at the ad. A new ad came up.");
  };

  appAds.banner.closedListener = () {
    print("You've closed an ad and returned to your app.");
  };

  appAds.screen.loadedListener = () {
    print("An ad has loaded into memory.");
  };

  appAds.screen.failedListener = () {
    print("An ad has failed to load in memory.");
  };

  appAds.screen.clickedListener = () {
    print("The opened ad was clicked on.");
  };

  appAds.screen.impressionListener = () {
    print("You've clicked on a link in the open ad.");
  };

  appAds.screen.openedListener = () {
    print("The ad has opened.");
  };

  appAds.screen.leftAppListener = () {
    print("The user has left the app and gone to the opened ad.");
  };

  appAds.screen.closedListener = () {
    print("The ad has been closed. The user returns to the app.");
  };

  appAds.video.loadedListener = () {
    print("An ad has loaded in memory.");
  };

  appAds.video.failedListener = () {
    print("An ad has failed to load in memory.");
  };

  appAds.video.clickedListener = () {
    print("An ad has been clicked on.");
  };

  appAds.video.openedListener = () {
    print("An ad has been opened.");
  };

  appAds.video.leftAppListener = () {
    print("You've left the app to view the video.");
  };

  appAds.video.closedListener = () {
    print("The video has been closed.");
  };

  appAds.video.rewardedListener = (String rewardType, int rewardAmount) {
    print("The ad was sent a reward amount.");
  };

  appAds.video.startedListener = () {
    print("You've just started playing the Video ad.");
  };

  appAds.video.completedListener = () {
    print("You've just finished playing the Video ad.");
  };

Add Up Ad Errors #

Below is a screenshot of some sample code implementing the error handling available to you when using the Dart package, Ads. By design, any exceptions that may occur in an event listeners' code is caught in a try..catch statement. The goal is to not crash the app for any reason involving AdMob ads. However, if and when an does error occurs, the developer has the means to determine the issue by collecting such errors in the List object, eventErrors. eventError

1.0.1 #

August 05, 2019

  • Renamed admob.dart

1.0.0 #

August 05, 2019

  • Internal rewrite readying class for public use
  • Deprecated hideBannerAd() & hideFullScreenAd()
  • List listeners to Set if(listener != null)
  • Replaced AdEventListener with MobileAdListener
  • Replaced VideoEventListener with RewardedVideoAdListener
  • testDevices.every((String s) => s == null || s.isNotEmpty))

0.12.0 #

August 01, 2019

  • Async setFullScreenAd hideFullScreenAd showBannerAd showFullScreenAd

0.11.0 #

July 11, 2019

  • bool removeVideo(VideoEventListener listener)

0.10.1 #

July 11, 2019

  • updated README.md with static reference example.

0.10.0 #

July 04, 2019

  • try..catch statements in event handlers.

0.9.2 #

July 03, 2019

  • Updated the file, README.md, include adding a Firebase project to your app.

0.9.1 #

June 29, 2019

  • Remove assert statements, assert(_firstObject, "An Ads class is already instantiated!");

0.9.0 #

June 25, 2019

  • Remove static properties and methods; Many set to library-private.
  • Using a generative constructor

0.8.2 #

June 27, 2019

  • Private constructor, Ads._():super();

0.8.1 #

June 22, 2019

  • Corrected showVideoAd() bug
  • Update README.md

0.8.0 #

June 21, 2019

  • Added all parameters to showBannerAd(), showFullScreenAd() and showVideoAd()
  • Add getter, childDirected.
  • Removed setters bannerUnitId, screenUnitId, videoUnitId, keywords, contentUrl
  • Removed getters appId, bannerUnitId, screenUnitId, videoUnitId
  • Deprecated getters bannerAd, fullScreenAd and videoAd

0.7.1 #

June 19, 2019

  • Supply the getter, testing.

0.7.0 #

June 19, 2019

  • Removed the property, testing.
  • Add testing parameter to 'set' functions.

0.6.1 #

June 19,2019

  • assert(appId != null && appId.isNotEmpty)
  • Semantic versioning ^0.9.0

0.6.0 #

June 10, 2019

  • Allow for multiple unitId's: One at init() and one when setting ads.
  • Removed the deprecated parameters: designedForFamilies and birthday

0.5.1 #

June 08, 2019

  • Allow for the most recent firebase_admob plugin in the example as well

0.5.0 #

June 08, 2019

  • Allow for always the most recent firebase_admob plugin

0.4.2 #

May 22, 2019

  • Provided setters for adUnitId
  • Clear memory variables before setting ad
  • Show Video after RewardedVideoAdEvent.loaded

0.4.1 #

May 21, 2019

  • if (adUnitId.isNotEmpty) _bannerUnitId = adUnitId.trim();

0.4.0 #

May 21, 2019

  • A distinction now between App id and Unit id
  • Each type of ad has been designated their own unit id.

0.3.0 #

April 02, 2019

  • Upgraded to firebase_admob: ^0.8.0 making this AndroidX compatible.
  • Note Those not wishing to use AndroidX support files must remain with 0.2.0.

0.2.0 #

March 24, 2019.

  • The named parameters, anchorOffset and anchorType, are supplied to the functions, showBannerAd() and showFullScreenAd()
  • Breaking Change As a consequence the named parameter, state, is now used in all the show() functions.

0.1.5+3 #

March 15, 2019.

  • Supplied a secure image for the YouTube Video onto README.md.

0.1.5+2 #

March 15, 2019.

  • Append YouTube Video onto README.md.

0.1.5+1 #

March 15, 2019.

  • Updated README.md.

0.1.5 #

March 15, 2019.

  • Provided API Documentation.

0.1.4 #

March 14, 2019.

  • Supplied a Homepage in pubspec.yaml

0.1.3 #

March 14, 2019.

  • Lengthened pubspec description.
  • Delete erroneous files
  • Delete folders, _windows & codestyles

0.1.2 #

March 14, 2019.

  • Corrected image in README.md
  • Format files

0.1.1 #

March 14, 2019.

  • Corrected images in README.md

0.1.0 #

March 14, 2019.

  • Initial Release
  • Remove deprecated fields: birthday, gender, designedForFamilies

0.1.0 #

December 11, ‎2018.

  • if (contentUrl == null || contentUrl.isEmpty) if(devices == null)

0.0.2 #

December 03, ‎2018.

  • sdk: ">=2.0.0 <5.0.0"

0.0.1 #

‎ May ‎29, ‎2018.

  • Initial Development Release

example/main.dart

// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/material.dart';
import 'dart:io' show Platform;
import 'package:firebase_admob/firebase_admob.dart';

import 'package:ads/ads.dart';

void main() {
  runApp(MyApp(initOption: 2));
}

class MyApp extends StatefulWidget {
  const MyApp({this.initOption, Key key}) : super(key: key);

  final int initOption;
  @override
  _MyAppState createState() => _MyAppState(initOption: initOption);
}

class _MyAppState extends State<MyApp> {
  _MyAppState({this.initOption = 1});

  Ads ads;
  final int initOption;
  int _coins = 0;

  final String appId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544~3347511713'
      : 'ca-app-pub-3940256099942544~1458002511';
  final String bannerUnitId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544/6300978111'
      : 'ca-app-pub-3940256099942544/2934735716';
  final String screenUnitId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544/1033173712'
      : 'ca-app-pub-3940256099942544/4411468910';
  final String videoUnitId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544/5224354917'
      : 'ca-app-pub-3940256099942544/1712485313';

  @override
  void initState() {
    super.initState();

    switch (initOption) {
      case 1:

        /// Assign a listener.
        var eventListener = (MobileAdEvent event) {
          if (event == MobileAdEvent.clicked) {
            print("The opened ad is clicked on.");
          }
        };

        ads = Ads(
          appId,
          bannerUnitId: bannerUnitId,
          screenUnitId: screenUnitId,
          videoUnitId: videoUnitId,
          keywords: <String>['ibm', 'computers'],
          contentUrl: 'http://www.ibm.com',
          childDirected: false,
          testDevices: ['Samsung_Galaxy_SII_API_26:5554'],
          testing: false,
          listener: eventListener,
        );

        break;

      case 2:
        ads = Ads(appId);

        /// Assign the listener.
        var eventListener = (MobileAdEvent event) {
          if (event == MobileAdEvent.closed) {
            print("User has opened and now closed the ad.");
          }
        };

        /// You can set the Banner, Fullscreen and Video Ads separately.

        ads.setBannerAd(
          adUnitId: bannerUnitId,
          size: AdSize.banner,
          keywords: ['andriod, flutter'],
          contentUrl: 'http://www.andrioussolutions.com',
          childDirected: false,
          testDevices: ['Samsung_Galaxy_SII_API_26:5554'],
          listener: eventListener,
        );

        ads.setFullScreenAd(
            adUnitId: screenUnitId,
            keywords: ['dart', 'flutter'],
            contentUrl: 'http://www.fluttertogo.com',
            childDirected: false,
            testDevices: ['Samsung_Galaxy_SII_API_26:5554'],
            listener: (MobileAdEvent event) {
              if (event == MobileAdEvent.opened) {
                print("An ad has opened up.");
              }
            });

        var videoListener = (RewardedVideoAdEvent event,
            {String rewardType, int rewardAmount}) {
          if (event == RewardedVideoAdEvent.rewarded) {
            print("The video ad has been rewarded.");
          }
        };

        ads.setVideoAd(
          adUnitId: videoUnitId,
          keywords: ['dart', 'java'],
          contentUrl: 'http://www.publang.org',
          childDirected: true,
          testDevices: null,
          listener: videoListener,
        );

        break;

      case 3:
        ads = Ads(appId);

        /// Assign the listener.
        var eventListener = (MobileAdEvent event) {
          if (event == MobileAdEvent.closed) {
            print("User has opened and now closed the ad.");
          }
        };

        /// You just show the Banner, Fullscreen and Video Ads separately.

        ads.showBannerAd(
          adUnitId: bannerUnitId,
          size: AdSize.banner,
          keywords: ['andriod, flutter'],
          contentUrl: 'http://www.andrioussolutions.com',
          childDirected: false,
          testDevices: ['Samsung_Galaxy_SII_API_26:5554'],
          listener: eventListener,
        );

        ads.showFullScreenAd(
            adUnitId: screenUnitId,
            keywords: ['dart', 'flutter'],
            contentUrl: 'http://www.fluttertogo.com',
            childDirected: false,
            testDevices: ['Samsung_Galaxy_SII_API_26:5554'],
            listener: (MobileAdEvent event) {
              if (event == MobileAdEvent.opened) {
                print("An ad has opened up.");
              }
            });

        var videoListener = (RewardedVideoAdEvent event,
            {String rewardType, int rewardAmount}) {
          if (event == RewardedVideoAdEvent.rewarded) {
            print("The video ad has been rewarded.");
          }
        };

        ads.showVideoAd(
          adUnitId: videoUnitId,
          keywords: ['dart', 'java'],
          contentUrl: 'http://www.publang.org',
          childDirected: true,
          testDevices: null,
          listener: videoListener,
        );

        break;

      default:
        ads = Ads(appId, testing: true);
    }

    ads.eventListener = (MobileAdEvent event) {
      switch (event) {
        case MobileAdEvent.loaded:
          print("An ad has loaded successfully in memory.");
          break;
        case MobileAdEvent.failedToLoad:
          print("The ad failed to load into memory.");
          break;
        case MobileAdEvent.clicked:
          print("The opened ad was clicked on.");
          break;
        case MobileAdEvent.impression:
          print("The user is still looking at the ad. A new ad came up.");
          break;
        case MobileAdEvent.opened:
          print("The Ad is now open.");
          break;
        case MobileAdEvent.leftApplication:
          print("You've left the app after clicking the Ad.");
          break;
        case MobileAdEvent.closed:
          print("You've closed the Ad and returned to the app.");
          break;
        default:
          print("There's a 'new' MobileAdEvent?!");
      }
    };

    MobileAdListener eventHandler = (MobileAdEvent event) {
      print("This is an event handler.");
    };

    ads.bannerListener = (MobileAdEvent event) {
      switch (event) {
        case MobileAdEvent.loaded:
          print("An ad has loaded successfully in memory.");
          break;
        case MobileAdEvent.failedToLoad:
          print("The ad failed to load into memory.");
          break;
        case MobileAdEvent.clicked:
          print("The opened ad was clicked on.");
          break;
        case MobileAdEvent.impression:
          print("The user is still looking at the ad. A new ad came up.");
          break;
        case MobileAdEvent.opened:
          print("The Ad is now open.");
          break;
        case MobileAdEvent.leftApplication:
          print("You've left the app after clicking the Ad.");
          break;
        case MobileAdEvent.closed:
          print("You've closed the Ad and returned to the app.");
          break;
        default:
          print("There's a 'new' MobileAdEvent?!");
      }
    };

    ads.removeBanner(eventHandler);

    ads.removeEvent(eventHandler);

    ads.removeScreen(eventHandler);

    ads.screenListener = (MobileAdEvent event) {
      switch (event) {
        case MobileAdEvent.loaded:
          print("An ad has loaded successfully in memory.");
          break;
        case MobileAdEvent.failedToLoad:
          print("The ad failed to load into memory.");
          break;
        case MobileAdEvent.clicked:
          print("The opened ad was clicked on.");
          break;
        case MobileAdEvent.impression:
          print("The user is still looking at the ad. A new ad came up.");
          break;
        case MobileAdEvent.opened:
          print("The Ad is now open.");
          break;
        case MobileAdEvent.leftApplication:
          print("You've left the app after clicking the Ad.");
          break;
        case MobileAdEvent.closed:
          print("You've closed the Ad and returned to the app.");
          break;
        default:
          print("There's a 'new' MobileAdEvent?!");
      }
    };

    ads.videoListener =
        (RewardedVideoAdEvent event, {String rewardType, int rewardAmount}) {
      switch (event) {
        case RewardedVideoAdEvent.loaded:
          print("An ad has loaded successfully in memory.");
          break;
        case RewardedVideoAdEvent.failedToLoad:
          print("The ad failed to load into memory.");
          break;
        case RewardedVideoAdEvent.opened:
          print("The ad is now open.");
          break;
        case RewardedVideoAdEvent.leftApplication:
          print("You've left the app after clicking the Ad.");
          break;
        case RewardedVideoAdEvent.closed:
          print("You've closed the Ad and returned to the app.");
          break;
        case RewardedVideoAdEvent.rewarded:
          print("The ad has sent a reward amount.");
          break;
        case RewardedVideoAdEvent.started:
          print("You've just started playing the Video ad.");
          break;
        case RewardedVideoAdEvent.completed:
          print("You've just finished playing the Video ad.");
          break;
        default:
          print("There's a 'new' RewardedVideoAdEvent?!");
      }
    };

    VoidCallback handlerFunc = () {
      print("The opened ad was clicked on.");
    };

    ads.banner.loadedListener = () {
      print("An ad has loaded successfully in memory.");
    };

    ads.banner.removeLoaded(handlerFunc);

    ads.banner.failedListener = () {
      print("An ad failed to load into memory.");
    };

    ads.banner.removeFailed(handlerFunc);

    ads.banner.clickedListener = () {
      print("The opened ad is clicked on.");
    };

    ads.banner.removeClicked(handlerFunc);

    ads.banner.impressionListener = () {
      print("The user is still looking at the ad. A new ad came up.");
    };

    ads.banner.removeImpression(handlerFunc);

    ads.banner.openedListener = () {
      print("You've closed an ad and returned to your app.");
    };

    ads.banner.removeOpened(handlerFunc);

    ads.banner.leftAppListener = () {
      print("You left the app and gone to the ad's website.");
    };

    ads.banner.removeLeftApp(handlerFunc);

    ads.banner.closedListener = () {
      print("You've closed an ad and returned to your app.");
    };

    ads.banner.removeClosed(handlerFunc);

    ads.screen.loadedListener = () {
      print("An ad has loaded into memory.");
    };

    ads.screen.removeLoaded(handlerFunc);

    ads.screen.failedListener = () {
      print("An ad has failed to load in memory.");
    };

    ads.screen.removeFailed(handlerFunc);

    ads.screen.clickedListener = () {
      print("The opened ad was clicked on.");
    };

    ads.screen.removeClicked(handlerFunc);

    ads.screen.impressionListener = () {
      print("You've clicked on a link in the open ad.");
    };

    ads.screen.removeImpression(handlerFunc);

    ads.screen.openedListener = () {
      print("The ad has opened.");
    };

    ads.screen.removeOpened(handlerFunc);

    ads.screen.leftAppListener = () {
      print("The user has left the app and gone to the opened ad.");
    };

    ads.screen.leftAppListener = handlerFunc;

    ads.screen.closedListener = () {
      print("The ad has been closed. The user returns to the app.");
    };

    ads.screen.removeClosed(handlerFunc);

    ads.video.loadedListener = () {
      print("An ad has loaded in memory.");
    };

    ads.video.removeLoaded(handlerFunc);

    ads.video.failedListener = () {
      print("An ad has failed to load in memory.");
    };

    ads.video.removeFailed(handlerFunc);

    ads.video.clickedListener = () {
      print("An ad has been clicked on.");
    };

    ads.video.removeClicked(handlerFunc);

    ads.video.openedListener = () {
      print("An ad has been opened.");
    };

    ads.video.removeOpened(handlerFunc);

    ads.video.leftAppListener = () {
      print("You've left the app to view the video.");
    };

    ads.video.leftAppListener = handlerFunc;

    ads.video.closedListener = () {
      print("The video has been closed.");
    };

    ads.video.removeClosed(handlerFunc);

    ads.video.rewardedListener = (String rewardType, int rewardAmount) {
      print("The ad was sent a reward amount.");
      setState(() {
        _coins += rewardAmount;
      });
    };

    RewardListener rewardHandler = (String rewardType, int rewardAmount) {
      print("This is the Rewarded Video handler");
    };

    ads.video.removeRewarded(rewardHandler);

    ads.video.startedListener = () {
      print("You've just started playing the Video ad.");
    };

    ads.video.removeStarted(handlerFunc);

    ads.video.completedListener = () {
      print("You've just finished playing the Video ad.");
    };

    ads.video.removeCompleted(handlerFunc);

    // Uncomment and run this example
//    List<String> one = ads.keywords;
//
//    String two = ads.contentUrl;
//
//    bool three = ads.childDirected;
//
//    List<String> four = ads.testDevices;
//
//    bool five = ads.initialized;
  }

  @override
  void dispose() {
    ads.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('AdMob Plugin example app'),
        ),
        body: SingleChildScrollView(
          child: Center(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                RaisedButton(
                    key: ValueKey<String>('SHOW BANNER'),
                    child: const Text('SHOW BANNER'),
                    onPressed: () {
                      ads.showBannerAd(state: this, anchorOffset: null);
                    }),
                RaisedButton(
                    key: ValueKey<String>('REMOVE BANNER'),
                    child: const Text('REMOVE BANNER'),
                    onPressed: () {
                      ads.closeBannerAd();
                    }),
                RaisedButton(
                  key: ValueKey<String>('SHOW INTERSTITIAL'),
                  child: const Text('SHOW INTERSTITIAL'),
                  onPressed: () {
                    ads.showFullScreenAd(state: this);
                  },
                ),
                RaisedButton(
                  key: ValueKey<String>('SHOW REWARDED VIDEO'),
                  child: const Text('SHOW REWARDED VIDEO'),
                  onPressed: () {
                    ads.showVideoAd(state: this);
                  },
                ),
                Text(
                  "You have $_coins coins.",
                  key: ValueKey<String>('COINS'),
                ),
              ].map((Widget button) {
                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 16.0),
                  child: button,
                );
              }).toList(),
            ),
          ),
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  ads: ^1.0.1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:ads/ads.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
86
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
93
Learn more about scoring.

We analyzed this package on Aug 21, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.4.0
  • pana: 0.12.19
  • Flutter: 1.7.8+hotfix.4

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Health suggestions

Format lib/admob.dart.

Run flutter format to format lib/admob.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
firebase_admob ^0.9.0 0.9.0+4
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.6 1.1.7
platform 2.2.1
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test