I want to load the ad first and showAd()
later. Although I use await on load, it still does not 'await' in InterstitialAdLoadCallback()
since it is a callback.
InterstitialAd? _interstitialAd;
print("OUTPUT 1");
await InterstitialAd.load(
adUnitId: '123456789',
request: AdRequest(),
adLoadCallback: InterstitialAdLoadCallback(
onAdLoaded: (ad) {
print("OUTPUT 2");
_interstitialAd = ad;
},
onAdFailedToLoad: (err) {
_interstitialAd = null;
},
),
);
print("OUTPUT 3");
Output:
OUTPUT 1
OUTPUT 3
OUTPUT 2
How to 'await' in InterstitialAdLoadCallback()
?
CodePudding user response:
If you want to await
an operation that does not directly expose a Future
, you can use a Completer
to create and manage one:
var adCompleter = Completer<void>();
InterstitialAd? _interstitialAd;
await InterstitialAd.load(
adUnitId: '123456789',
request: AdRequest(),
adLoadCallback: InterstitialAdLoadCallback(
onAdLoaded: (ad) {
_interstitialAd = ad;
adCompleter.complete();
},
onAdFailedToLoad: (err) {
_interstitialAd = null;
adCompleter.completeError(err);
},
),
);
await adCompleter.future;