Admob Flutter AppBar Banner Recipe

08/05/2020

Hi 👋🏻

Looking to monetize your app? Of course, that’s how you ended up on this page. I’m a maintainer of the Flutter package admob_flutter and I’m here to help. 😉

There are many approaches to placing banner ads in an app. This isn’t the only way but a pretty cool way to use extensions, remove boilerplate, and not reinvent the wheel.

Dart Extensions

Extensions were introduced in Dart 2.7. Extensions allow extending library functionality without controlling the original package.

I’ve added to the example app withBottomAdmobBanner. An extension that will append an ADAPTIVE_BANNER to the bottom of an AppBar.

Not only will the extension append to the bottom of the AppBar, but it also implements PreferredSizeWidget, which is required to be used as an AppBar. This ensures that the AppBar and the height of the banner are taken into consideration. This way your Scaffold’s body will never overlap the banner. An added benefit is this aligns with Admob Banner policy which encourages fixed spaces for banners. This way your entire content doesn’t shift after things load. This can cause accidental clicks.

Once you import the extension, adding a banner ad is as simple as adding .withBottomAdmobBanner(context) to you AppBar. Check out the code sample below. Easy peasy!

import 'package:flutter/material.dart';
import 'package:admob_flutter_example/extensions.dart'; // import the extension

class NewPage extends StatelessWidget {
  final String title;
  const NewPage({
    Key key,
    @required this.title,
  }) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
        brightness: Brightness.dark,
      ).withBottomAdmobBanner(context), // Add this
    );
  }
}

Demo

Here is the extension in action when I load a new page.

demo

You can check out the rest of the code on Github.

ADAPTIVE_BANNER and Customization

I always use ADAPTIVE_BANNER since it is extremely flexible. withBottomAdmobBanner by default will fill the width of the screen. The height I have hardcoded the below snippet which you are free to change to fit your needs. I thought this height worked fairly well.

double get height => max(size.height * .06, 50.0);

This example takes 6% of the window height OR 50, whichever is larger. I like to stay away from fixed sizes in my Flutter apps. This helps adjust nicely when running on any size window like tablets, web, and desktop.

Just copy and paste the extension into your app and make any modifications you see fit.

Thank You!

Tips Appreciated! ☕️ Cheers!