mnemo_cards/lib/features/yandex_ads/yandex_ads.dart
2024-07-27 16:13:42 +03:00

95 lines
2.7 KiB
Dart

import 'dart:async';
import 'dart:developer';
import 'package:flutter/widgets.dart';
import 'package:yandex_mobileads/mobile_ads.dart';
class YandexAds {
static BannerAd createBanner(
BoxConstraints constraints, {
required String id,
String? key,
VoidCallback? onLoaded,
}) {
return BannerAd(
adUnitId: id,
// or 'demo-banner-yandex'
adSize: BannerAdSize.inline(
width: constraints.maxWidth.round(),
maxHeight: constraints.maxHeight.round(),
),
adRequest: const AdRequest(),
onAdLoaded: () {
log('Loaded $key');
onLoaded?.call();
},
onAdFailedToLoad: (error) {
// Ad failed to load with AdRequestError.
// Attempting to load a new ad from the onAdFailedToLoad() method is strongly discouraged.
},
onAdClicked: () {
// Called when a click is recorded for an ad.
},
onLeftApplication: () {
// Called when user is about to leave application (e.g., to go to the browser), as a result of clicking on the ad.
},
onReturnedToApplication: () {
// Called when user returned to application after click.
},
onImpression: (impressionData) {
// Called when an impression is recorded for an ad.
});
}
static RewardedAd? _preloadedAd;
static Future<RewardedAd?> loadRewardedAd() async {
final completer = Completer<RewardedAd?>();
final _rewardedAdLoader = await RewardedAdLoader.create(
onAdLoaded: (RewardedAd rewardedAd) {
_preloadedAd = rewardedAd;
completer.complete(rewardedAd);
},
onAdFailedToLoad: (error) {
completer.complete(null);
},
);
await _rewardedAdLoader.loadAd(
adRequestConfiguration: AdRequestConfiguration(
adUnitId: 'R-M-3761037-1',
),
);
return completer.future;
}
static Future<bool> showRewardedAd(
Function(Reward reward) onRewarded, {
maxAttempts = 2,
}) async {
if (_preloadedAd == null) {
final _loadedAd = await loadRewardedAd();
if (_loadedAd == null) {
return false;
}
}
final _ad = _preloadedAd;
_preloadedAd = null;
_ad?.setAdEventListener(
eventListener: RewardedAdEventListener(onAdDismissed: () {
_ad.destroy();
}, onAdFailedToShow: (e) {
_ad.destroy();
if (maxAttempts-- > 0) {
showRewardedAd(onRewarded, maxAttempts: maxAttempts);
}
}, onAdShown: () {
// _ad.destroy();
}, onRewarded: (r) {
onRewarded(r);
_ad.destroy();
}));
await _ad?.show();
final reward = await _ad?.waitForDismiss();
return reward != null;
}
}