Creating a rewarded ad (rewardedAd) with Admob in Flutter

Tiempo de lectura: 3 minutos

Today we are going to learn how we can add a Rewarded ad with Admob in Flutter

The first thing we are going to do is create the file with our ad IDs, for this we have to go to Admob and obtain the code that will allow us to add the banner.

Now we are going to create this file: idsAnuncios.dart

import 'dart:io';

const test = false;

String getIdRewarded() {
  var bannerId = "ca-app-pub-3940256099942544/6300978111";
  if (Platform.isAndroid) {
    if (!test) {
      //Real ads
      bannerId = "your_ad_banner_id_ANDROID";
    } else {
      //Test ads
      bannerId = "ca-app-pub-3940256099942544/5224354917";
    }
  } else if (Platform.isIOS) {
    if (!test) {
      //Real ads
      bannerId = "your_ad_banner_id_iOS";
    } else {
      //Test ads
      bannerId = "ca-app-pub-3940256099942544/1712485313";
    }
  }
  return bannerId;
}

We have added a variable that will allow us to put the ads in test mode.

We have added the test banner ad IDs that Admob offers by default.

In addition, we assign ads for Android and iOS.

Where your_copied_code is indicated, you add the Admob code you have created.

Now we are going to add the library that will allow us to use Google ads:

google_mobile_ads

For that:

flutter pub add google_mobile_ads

In addition, we will have to add the following within pubspec.yaml to increase the minimum SDK to 2.12.0 and allow null safety

environment:
  # TODO: Update the minimum sdk version to 2.12.0 to support null safety.
  sdk: ">=2.17.0 <3.0.0"

Note: in my case by this date it already generates the projects with this version:

Now we open our AndroidManifest file inside the directory: android/app/src/main/AndroidManifest.xml

And we add the application code:

<manifest>
    ...
    <application>
       ...
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-3940256099942544~3347511713"/>
    </application>

</manifest>

In case of iOS you must add within info.plist

<

pre class=”EnlighterJSRAW” data-enlighter-language=”generic” data-enlighter-theme=”” data-enlighter-highlight=”” data-enlighter-linenumbers=”” data-enlighter-lineoffset=”” data-enlighter-title=”” data-enlighter-group=””>

Note:
Test APP ID: <codehtml
Copy code

ca-app-pub-3940256099942544~334751171

You must add your own, generated from Admob.

Now let’s go to our main screen and initialize the ads with this function:

 Future<InitializationStatus> _initGoogleMobileAds() {
    // TODO: Initialize Google Mobile Ads SDK
    return MobileAds.instance.initialize();
  }

And now we are going to create the rewarded ad.

rewarded.dart

<

pre class=”EnlighterJSRAW” data-enlighter-language=”generic” data-enlighter-theme=”” data-enlighter-highlight=”” data-enlighter-linenumbers=”” data-enlighter-lineoffset=”” data-enlighter-title=”” data-enlighter-group=””>import ‘package:flutter/material.dart’;
import ‘package:google_mobile_ads/google_mobile_ads.dart’;
import ‘package:walls_wallpapers/util/idsAnuncios.dart’;

class AdRewarded {
static RewardedAd? _rewardedAd;

static Future<void> initialize() async {
await _loadRewardedAd();
}

static Future<void> _loadRewardedAd() async {
RewardedAd.load(
adUnitId: AdHelper.rewardedAdUnitId,
request: AdRequest(),
rewardedAdLoadCallback: RewardedAdLoadCallback(
onAdLoaded: (RewardedAd ad) {
print(‘Rewarded Ad loaded’);
_rewardedAd = ad;
},
onAdFailedToLoad: (LoadAdError error) {
print(‘Rewarded Ad failed to load: $error’);
},
),
);
}

static void showRewardedAd(
{required Function onReward, required Function onDimiss}) {
if (_rewardedAd == null) {
print(‘Rewarded Ad not loaded yet.’);
onDimiss();
//onReward(-1);
return;
}

_rewardedAd!.fullScreenContentCallback = FullSchtml

Copy code

ca-app-pub-3940256099942544~334751171

You must add your own, generated from Admob.

Now let’s go to our main screen and initialize the ads with this function:

 Future<InitializationStatus> _initGoogleMobileAds() {
    // TODO: Initialize Google Mobile Ads SDK
    return MobileAds.instance.initialize();
  }

And now we are going to create the rewarded ad.

rewarded.dart

import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:walls_wallpapers/util/idsAnuncios.dart';

class AdRewarded {
  static RewardedAd? _rewardedAd;

  static Future<void> initialize() async {
    await _loadRewardedAd();
  }

  static Future<void> _loadRewardedAd() async {
    RewardedAd.load(
      adUnitId: AdHelper.rewardedAdUnitId,
      request: AdRequest(),
      rewardedAdLoadCallback: RewardedAdLoadCallback(
        onAdLoaded: (RewardedAd ad) {
          print('Rewarded Ad loaded');
          _rewardedAd = ad;
        },
        onAdFailedToLoad: (LoadAdError error) {
          print('Rewarded Ad failed to load: $error');
        },
      ),
    );
  }

  static void showRewardedAd(
      {required Function onReward, required Function onDimiss}) {
    if (_rewardedAd == null) {
      print('Rewarded Ad not loaded yet.');
      onDimiss();
      //onReward(-1);
      return;
    }

    _rewardedAd!.fullScreenContentCallback = FullScreenContentCallback(
      onAdDismissedFullScreenContent: (Ad ad) {
        print('Rewarded Ad dismissed');
        onDimiss();
        _loadRewardedAd(); // Load a new ad after the current one has been shown.
      },
    );

    _rewardedAd!.show(
      onUserEarnedReward: (AdWithoutView ad, RewardItem reward) {
        print('User earned reward: ${reward.amount}');
        onReward(reward
            .amount); // Call the callback when the user earns a reward.
      },
    );
  }

  static void dispose() {
    _rewardedAd?.dispose();
  }
}

class AdHelper {
  static String rewardedAdUnitId = getIdRewarded();
}

And now we must initialize it in main.dart

AdRewarded.initialize();

And now we can invoke it from wherever we want.

AdRewarded.showRewardedAd(
      onReward: (value) {
        print('User was rewarded for watching an ad. $value');
        // Here you can add the code that will run when the user earns a reward.
      },
      onDimiss: () {
        print('User dismissed the ad without watching the full video.');
        // Here you can add the code that will run when the user closes the ad without watching the full video.
      },
);

And this is the result:

Leave a Comment