ads 0.2.0

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • new80

Ads in your App in a Snap! #

A Flutter Example #

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

Ads by Example #

In the first example listed below, it takes only three lines of code, to get a banner ad displayed in your app. All that's required of you is the 'AdMob id' you got when you signed up for an Adsense account. The id listed here is a 'test id' offered by Google and is to be used during development. Of course, keep yours confidential, but when using yours during development, supply instead the second parameter, testing, to the init() function. Doing so, as you see in the example below, and setting it to true will bring up only 'test ads.'

Flutter AdMob

AdMob by Google #

If you've yet to get setup for AdMob, go to this website, https://firebase.google.com/docs/admob/, after downloading this file. You'll need your 'AdMob id.' Again, test id's are supplied by the plugin to be used during development since using your own id would violate 'AdMob by Google' policy. I mean, you can't be clicking ads on your own app, don't you know! That'd be cheating!

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

Just Three Lines Of Code #

Three lines of code, and you've a Banner ad. It's best practice to call the 'Ads' init() function in a State object's iniState() function, and to call its dispose() function in the State object's corresponding dispose() function. The third function call is showBannerAd() and, as the name implies, it does just that.

Beta You Bet! #

Again, this 'Ads' library currently uses the plugin, firebase_admob, which is, as of this writing, 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.

You've Got Options #

Anyone who's read my past articles knows I'm always looking for options. We software developers love options, right? Well, of course, using this library, you've got options. You can see, in the second example below, along with the required 'AdMob id', you've got nine other settings you can optionally use to describe the kind of ads you may wish to be associated with your app.

Nine named parameters that match the named parameters used by the plugin.

Ten options to initialize and display an AdMob Banner ad.

'Setter' Your Options #

So you see, you can supply these options directly in the init() function. However, you could also specify just one or two individually before showing your ads. I'm always looking for options: The Setters in the Ads Library.

There's Getters and Setters #

Of course, as well as setting them, you can readily retrieve the values of these settings if you need to for one reason or another. Below, you can see there are just as many getters as there are setters in this 'Ads' class. And so, you or another developer working on another part of the app have ready access to all the settings currently available by this 'Ads' class and consequently currently available by the firebase_admob plugin.

The Getters in the Ads Library.

It's All Static #

As you can deduce by now, this 'Ads' class is using only static members and methods. This means they can be accessed or changed any time and anywhere in your app. Makes it that much easier to deal with ads in your app.

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! #

Looking inside the plugin, we see it 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 time an individual ad is displayed in your app. I'm not certain however as there's not much API documentation for this plugin at the time of this writing either.

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. Look at the example below. The 'Ads.eventListener' is the granddaddy of event listeners for this library. With all the events the plugin watches out for, you can use this event listener to catch the ones you're particular interested in. It applies to the types of events shared by all three types of ads.

Ads Event Listener Example.

Listen Up! #

Again, you have three types of ads, and so, instead of using that 'granddaddy' listener above, each has its own set of event listeners. There's the bannerListener, the screenListner, and the videoListener. As you know, 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.

Three 'type' of Event Listeners are available.

Let's Get Specific #

However, you know me, there's other options. Again, that 'granddaddy' event listener could get a little messy - what with possibly a very long switch-case statement and all those MobileAdEvent options. How about not just targeting the type of Ad, but instead targeting one particular event? How about assigning any number of event listeners to just one particular event? How about that? 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. Below, we've got two listeners that both fire when the Banner ad is clicked on and opened, we've got another when the user is leaving the app to then view the ad, and the last one when the ad from the Banner ad is closed, and the user is now returning to the app. How about that?

Banner Listeners

As you've likely suspected, the Full-screen ad also has the same array of event listeners like the Banner ad. Again, there's seven separate events you can individually assign an event listener - and as many listeners as you like at that. How about that!

Full-Screen Listeners

Finally, you guessed it, the Video ad also has all the event listeners needed to catch each of all the possibly events currently issued to it by the firebase_admob plugin-eight events as of this writing. Below, there's an example of how to 'reward' a passed amount when the user has finished viewing a video.

Video Event Listeners Example

Clean Up After Your Ads #

Display ads do take up resources. This 'Ads' library therefore provides you the means to clean up after yourself when you may want to close your ads at some point for some reason. Also, you're free to hide and then show them again if you like. You're able to 'clear' any listeners at any point as well - either individually or in one fell swoop!

Ads Cleaner Listeners

It's All in the Setup #

As you see in the example below, you've options galore! You can setup all three types of ads with the one-time call to the init() function or individually because each type has their own 'set' function: setBannerAd(), setFullScreenAd() and setVideoAd(). Why would you do such a thing? Who knows! What am I…a mindreader?! Maybe you've got different plans for each type of ad. Regardless, you've got that option.

Ways to setup for AdMob ads.

A Flutter Example #

The PUB website offers an example on how to implement the firebase_admob plugin. I've included that example in the following gist, AdMob in Flutter Example. However, you guessed it, this example instead uses the 'Ads' library to demonstrate ads in a Flutter app. Below is the main.dart file found in the example. I've highlighted where the 'Ads' class library is used.

main.dart for AdMob Example

Conclusion #

This library was offered to you merely to make your life a little easier when it comes to displaying ads in your app. It may have its short-comings, but this simply is my way of contributing to our fledgling Flutter community. Flutter is the way to go in my opinion, and sharing code is one way to help make this community grow and go forward.

YouTube Video #

Flutter AdMob Video

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 'package:ads/ads.dart';
import 'package:prefs/prefs.dart';

import 'package:firebase_admob/firebase_admob.dart';

import 'package:mvc_pattern/mvc_pattern.dart';

// You can also test with your own ad unit IDs by registering your device as a
// test device. Check the logs for your device's ID value.
const String testDevice = 'Samsung_Galaxy_SII_API_26:5554';

const String ADS_PREF = 'ads';

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends StateMVC {
  int _coins = 0;

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

    var initOption = 1;

    switch (initOption) {
      case 1:
        Ads.init('ca-app-pub-3940256099942544', testing: true);

        Ads.video.rewardedListener = (String rewardType, int rewardAmount) {
          setState(() {
            _coins += rewardAmount;
          });
        };
        break;

      case 2:
        var eventListener = (MobileAdEvent event) {
          if (event == MobileAdEvent.opened) print("Returned to the app.");
        };

        Ads.init(
          'ca-app-pub-3940256099942544',
          keywords: <String>['ibm', 'computers'],
          contentUrl: 'http://www.ibm.com',
          childDirected: false,
          testDevices: ['Samsung_Galaxy_SII_API_26:5554'],
          testing: false,
          listener: eventListener,
        );

        break;

      case 3:
        var eventListener = (MobileAdEvent event) {
          if (event == MobileAdEvent.closed) print("Returned to the app.");
        };

        Ads.init('ca-app-pub-3940256099942544',
            listener: eventListener, testing: true);

        // You can set individual settings
        Ads.keywords = ['cats', 'dogs'];
        Ads.contentUrl = 'http://www.animalsaspets.com';
        Ads.childDirected = false;
        Ads.testDevices = ['Samsung_Galaxy_SII_API_26:5554'];
        Ads.testing = true;
        Ads.bannerListener = (MobileAdEvent event) {
          if (event == MobileAdEvent.opened) {
            print("This is the first listener.");
          }
        };

        break;

      case 4:
        Ads.init('ca-app-pub-3940256099942544');

        var eventListener = (MobileAdEvent event) {
          if (event == MobileAdEvent.closed) print("Returned to the app.");
        };

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

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

        Ads.setFullScreenAd(
            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("Opened the Ad.");
            });

        var videoListener = (RewardedVideoAdEvent event,
            {String rewardType, int rewardAmount}) {
          if (event == RewardedVideoAdEvent.closed) {
            print("Returned to the app.");
          }
        };

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

        break;
      case 5:
        Ads.init('ca-app-pub-3940256099942544');

        /// You can set individual settings
        Ads.keywords = ['cats', 'dogs'];
        Ads.contentUrl = 'http://www.animalsaspets.com';
        Ads.childDirected = false;
        Ads.testDevices = ['Samsung_Galaxy_SII_API_26:5554'];

        /// Can set this at the init() function instead.
        Ads.testing = true;

        break;

      case 6:
        Ads.init('ca-app-pub-3940256099942544', testing: true);

        Ads.eventListener = (MobileAdEvent event) {
          switch (event) {
            case MobileAdEvent.loaded:
              print(
                  "The Ad is loading into memory. Not necessarily displayed yet.");
              break;
            case MobileAdEvent.failedToLoad:
              print("The Ad failed to load into memory.");
              break;
            case MobileAdEvent.clicked:
              print("The Ad has been clicked and opened.");
              break;
            case MobileAdEvent.impression:
              print("The displayed Ad has 'changed' to a new one.");
              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?!");
          }
        };

        break;

      case 7:
        Ads.init('ca-app-pub-3940256099942544', testing: true);

        Ads.showBannerAd(state: this);

        Ads.bannerListener = (MobileAdEvent event) {
          if (event == MobileAdEvent.opened) {
            print("You've clicked on the Banner Ad");
          }
        };

        Ads.screenListener = (MobileAdEvent event) {
          if (event == MobileAdEvent.opened) {
            print("You've clicked on the Fullscreen Ad.");
          }
        };

        Ads.videoListener = (RewardedVideoAdEvent event,
            {String rewardType, int rewardAmount}) {
          if (event == RewardedVideoAdEvent.opened) {
            print("You've clicked on the Fullscreen Ad.");
          }
        };

        break;
      case 8:
        Ads.init('ca-app-pub-3940256099942544', testing: true);

        Ads.banner.openedListener = () {
          print("This is the first listener when you open the banner ad.");
        };

        Ads.banner.openedListener = () {
          print("This is the second listener when you open the banner ad.");
        };

        Ads.banner.leftAppListener = () {
          print("You've left your app.");
        };

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

        break;
      case 9:
        Ads.init('ca-app-pub-3940256099942544', testing: true);

        Ads.screen.openedListener = () {
          print("This is the first listener when you open the full screen ad.");
        };

        Ads.screen.openedListener = () {
          print(
              "This is the second listener when you open the full screen ad.");
        };

        Ads.screen.leftAppListener = () {
          print("You've left your app.");
        };

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

        break;
      case 10:
        Ads.init('ca-app-pub-3940256099942544', testing: true);

        Ads.video.closedListener = () {
          print("You've closed the video.");
        };

        Ads.video.rewardedListener = (String rewardType, int rewardAmount) {
          setState(() {
            _coins += rewardAmount;
          });
        };

        break;

      default:
        Ads.init('ca-app-pub-3940256099942544', testing: true);
    }

    var one = Ads.appId;
    var two = Ads.keywords;
    var three = Ads.contentUrl;

    var seven = Ads.childDirected;
    var eight = Ads.testDevices;
    var nine = Ads.testing;

    showAd();
  }

  void showAd() async {
    String adType = await Prefs.getStringF(ADS_PREF);

    switch (adType) {
      case 'screen':
        Ads.showFullScreenAd(state: this);
        break;
      case 'video':
        Ads.showVideoAd(state: this);
        break;
      default:
        Ads.showBannerAd(state: this);
    }
  }

  @override
  void dispose() {
    Prefs.dispose();
    Ads.dispose();
    super.dispose();
  }

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

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

Use this package as a library

1. Depend on it

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


dependencies:
  ads: ^0.2.0

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter packages get

Alternatively, your editor might support flutter packages 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';
  
Version Uploaded Documentation Archive
0.2.0 Mar 24, 2019 Go to the documentation of ads 0.2.0 Download ads 0.2.0 archive
0.1.5+3 Mar 15, 2019 Go to the documentation of ads 0.1.5+3 Download ads 0.1.5+3 archive
0.1.5+2 Mar 15, 2019 Go to the documentation of ads 0.1.5+2 Download ads 0.1.5+2 archive
0.1.5+1 Mar 15, 2019 Go to the documentation of ads 0.1.5+1 Download ads 0.1.5+1 archive
0.1.5 Mar 15, 2019 Go to the documentation of ads 0.1.5 Download ads 0.1.5 archive
0.1.4 Mar 14, 2019 Go to the documentation of ads 0.1.4 Download ads 0.1.4 archive
0.1.3 Mar 14, 2019 Go to the documentation of ads 0.1.3 Download ads 0.1.3 archive
0.1.2 Mar 14, 2019 Go to the documentation of ads 0.1.2 Download ads 0.1.2 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
61
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]
80
Learn more about scoring.

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

  • Dart: 2.2.0
  • pana: 0.12.14
  • Flutter: 1.3.3

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Dependencies

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