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 loadRewardedAd() async { final completer = Completer(); 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 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; } }