Prefetch Google Mobile Ads in Flutter
Published: 2023-05-22 11:29:07


## Prefetch Google Mobile Ads in Flutter

Hey Geeks🧑‍💻! **I’m Aayush Sharma**, your friendly Flutter Developer. Recently, I encountered a fascinating challenge while working on a large-scale production app. Today, I’m excited to share my discoveries and the solutions I implemented to overcome these hurdles.

Before we begin! Here’s a Cat harassing a robot vacuum.

![](https://cdn-images-1.medium.com/max/2000/1*17jO5F2Gyq_2VZW7V5XLXg.gif)

Let’s dive in 🥽

## The Challenge 🧩

**Ads can serve as the sole source of revenue for certain apps**. They provide a significant income stream for app developers and publishers, helping to monetize the app and generate funds for ongoing development and maintenance expenses. However, if the ads fail to load quickly and disrupt user engagement, it becomes a significant obstacle.

I encountered a challenge when I needed to display ads between articles in a PageView. Despite having a good internet connection, **the ads typically took 3–4 seconds to load**. However, users are lightning-fast when it comes to scrolling past a blank screen, taking less than a second to move on. As a result, **user engagement and ad impressions were completely eliminated**.

In this article, **I’ll show you how you can prefetch Ads in a Pageview** the correct way without wasting any resources.

## Please Note🛑

This article isn’t about how to implement Ads in Flutter. **I assume that you are familiar with integrating Google mobile Ads**, If not I suggest you go through this [doc](https://developers.google.com/admob/flutter/quick-start).

**I won’t be using a real AdMob account** and will be showing you a demo of my production App with some minor changes.

## Project Overview 🚧

We’ll be working with a demo App that will have only one screen - A Pageview in which every page shows a random image from [Unsplash](https://unsplash.com/) and after every 4th card there will be an Ad. We’ll be using [Provider](https://pub.dev/packages/provider) for state management.

You can find the base code for the app [here](https://github.com/Ayush783/flutter_ads_pageview). Attaching the initial video of the app before prefetching.

## The Logic for Prefetching Ad 🧠

The logic for prefetching ads is simple, We’ll be maintaining a BannerAd object in our provider and **call the load() method on it with the required configuration, 2–3 pages before showing the AdPage.**

We’ll need to carefully dispose of and reinitialize it to avoid any resource leaks and runtime errors.

The Github gist below provides the logic for loading the Ad.
{% gist https://gist.github.com/Ayush783/f9ecdbdf3338ebcbd3e916bfeb648594.js %}
Summarising the above code:-

* We maintain a nullable instance of the BannerAd object and provide its getter and setter.

* In the load() method, we first dispose of the _bannerAd object if there is any.

* Then reinitialize it using the constructor provided by BannerAd and providing the Ad unit id.

* Lastly, call the load() method on _bannerAd.

Add a dispose method to handle the disposing of the Ad.
{% gist https://gist.github.com/Ayush783/814deae79832bac60e9e635c4171c32e.js %}
Optionally you can add a boolean flag to check the loading status of the Ad. The final code is given in the following gist.
{% gist https://gist.github.com/Ayush783/84098cfc631f2f559baeba67823f4302.js %}
## Final Changes 🏁

Now we just need to integrate these changes into the presentation logic.

Firstly in your image_pageview.dart file load the first Ad in the initState() method.
{% gist https://gist.github.com/Ayush783/75a41bc84aba65f59fde8e9bae82a7ab.js %}
Add the logic to load Ad in the onPageChanged attribute of the PageView. We’ll be loading the Ad 2 pages before the actual AdPage.
{% gist https://gist.github.com/Ayush783/a39131f0cefc90f3ac9ad9ec94296a41.js %}
Call the disposeAd() method in the deactivate method of the ImagePageview widget.
{% gist https://gist.github.com/Ayush783/28938e8be28e2f66007bdd70d2c3d0db.js %}
In AdPage.dart watch the values of BannerAd Object and loadingAd Boolean value, as follows.

    final bannerAd = context.watch<MyAdProvider>().bannerAd;
    final loadingAd = context.watch<MyAdProvider>().loadingAd;

Now the final thing is to change the implementation of how AdWidget is displayed. Minor changes are to be made as follows.

    SizedBox(
      width: 380,
      height: 420,
      child: bannerAd != null && !loadingAd
             ? AdWidget(
                 ad: context.read<AppProvider>().bannerAd!,
             )
             : const SizedBox(),
    )

Below is the final code for AdPage.
{% gist https://gist.github.com/Ayush783/204cd7f9e7600c635ad95a6582e48ae3.js %}
## Final Result 🎉

Here are the final results of prefetching Ads. **It will increase Ad impressions in your App drastically**. You can find the completed project [**here](https://github.com/Ayush783/flutter_ads_pageview)**.

## Negative Impact of Ads Loading Slow 📉

* **Increased Abandonment**: Users are more likely to abandon an app that takes forever to load ads.

* **Disrupted User Flow**: We want our users to flow smoothly through the app, and not get stuck in an ad traffic jam.

* **Lower Ad Viewability**: Users zip past slow-loading ads faster than Superman chasing a speeding bullet.

* **Decreased Revenue Potential**: Slow-loading ads can be a real buzzkill for our revenue dreams. It’s like trying to sell ice cream in Antarctica — sure, it’s a great product, but who’s gonna stick around long enough to buy it?

* **Negative Brand Perception**: Apps with slow-loading ads may be perceived as unprofessional or poorly optimized, damaging the brand image and trust of users.

## Benefits of loading Ads faster 🏆

* **Improve user experience**. Slow-loading ads can frustrate users and lead them to uninstall your app.

* **Increase engagement**. When ads load quickly, users are more likely to interact with them. **This can lead to increased click-through rates and conversions**.

* **Boost revenue**. Faster-loading ads can help you earn more money. This is because **users are likelier to watch or click on ads** that load quickly.

* **Improve app ranking**. Google Play and the App Store consider app performance when ranking apps. This means that **apps with faster-loading ads are more likely to rank higher** in the app store.

Well, I’ll be ending this article here. I hope you learned something new today😊. You can reach out to me on [**LinkedIn](https://www.linkedin.com/in/ayushb58/)** or [**Twitter](https://twitter.com/Ayush_b5)** in case of any queries. I’ll be more than happy to help.