DEV Community

Pere Sola
Pere Sola

Posted on • Updated on


Display Admob ads in your Flutter app

-0. Sign up to Admob & docs here.

-1. Install the Flutter google_mobile_ads package and follow the few instructions here.

-2. Initialise the library, like so:

void main() {
  WidgetsFlutterBinding.ensureInitialized(); // this line
  MobileAds.instance.initialize(); // and this line

  runApp(const MyApp());
Enter fullscreen mode Exit fullscreen mode

-3. When you run the app (flutter run), you will probably be asked to bump the minSdkVersion to 19 (as of 19/01/2023). Do so in android\app\build.gradle.

-4. When you run the app again, you will probably get a warning about Google Mobile Ads SDK initialized incorrectly:

Image description

Let's follow the instructions here. Even better, follow them in the Flutter section of their docs.

-5. A little gotcha is that

Enter fullscreen mode Exit fullscreen mode

goes inside <application></application>tags, I got the location wrong the first time because there are other meta-data tags inside <activity />.

-6. Follow the implementation instructions for the app unit you want, in my case Banner.

-7. The ad unit needs to be created from you Admob dashboard - each one of them seems to have an id. You need to add it to the instantiated BannerAd:

Image description

Image description

-8. Google offers test ad units (not app ids..) for test, see here.

-9. Do not build in Chrome, it will only work on Android or iOS (see issue here).

-10. You may not want to write your app id in the manifest file because you are committing the file to source control. In that case, you can pass env-variables at build time and write come code so they can be used in your code at run time. More instructions here: The env variables are passed at build time like so: flutter build --dart-define SUPER_SECRET_API_KEY={ADD_THE_API_KEY_HERE} --dart-define SOME_OTHER_STUFF={THE_WHATEVER_YOU_NEED_HERE}. Same for flutter run. If you need to access a variable in your dart code, you access it with:

const String.fromEnvironment(
        defaultValue: 'whatever_is_the_default_value_if_it_fails_somehow',
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

50 CLI Tools You Can't Live Without

The top 50 must-have CLI tools, including some scripts to help you automate the installation and updating of these tools on various systems/distros.