Closed4

[flutter] admob でバナー広告を設置

はやぶさはやぶさ

AdWidgetを配置するだけではダメで、適宜BannerAd を load(), dispose() する必要があるのが若干めんどくさい

はやぶさはやぶさ

以下のような感じでうまく動いている。
flutter_hooks 使用

ad_banner.dart
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:fugu_diary/foundation/util/logger.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

const testBannerUnitIOSId = 'ca-app-pub-3940256099942544/2934735716';
const testBannerUnitAndroidId = 'ca-app-pub-3940256099942544/6300978111';
const bannerUnitIOSId = 'XXXX'; // admobに登録して得たidを入力
const bannerUnitAndroidId = 'XXXX'; // admobに登録して得たidを入力

String get adBannerUnitId {
  if (Platform.isIOS) {
    return flavor == Flavor.prod ? bannerUnitIOSId : testBannerUnitIOSId;  // Flavorは自前で別に定義
  } else if (Platform.isAndroid) {
    return flavor == Flavor.prod ? bannerUnitAndroidId : testBannerUnitAndroidId;
  }

  unreachableError(Platform());
}


BannerAd newAdBanner(AdSize size) => BannerAd(
      adUnitId: adBannerUnitId,
      size: size,
      request: const AdRequest(),
      listener: BannerAdListener(
        // Called when an ad is successfully received.
        onAdLoaded: (Ad ad) => logger.d('Ad loaded.'),
        // Called when an ad request failed.
        onAdFailedToLoad: (Ad ad, LoadAdError error) {
          // Dispose the ad here to free resources.
          ad.dispose();
          logger.i('Ad failed to load: $error');
        },
        // Called when an ad opens an overlay that covers the screen.
        onAdOpened: (Ad ad) => logger.d('Ad opened.'),
        // Called when an ad removes an overlay that covers the screen.
        onAdClosed: (Ad ad) => logger.d('Ad closed.'),
        // Called when an impression occurs on the ad.
        onAdImpression: (Ad ad) => logger.d('Ad impression.'),
      ),
    );

class AdBanner extends HookConsumerWidget {
  const AdBanner({this.size = AdSize.banner}) : super();

  final AdSize size;

  
  Widget build(BuildContext context, WidgetRef ref) {
    final adBanner = useMemoized(() => newAdBanner(size)..load());
    useEffect(() => adBanner.dispose, []);
    return Container(
      alignment: Alignment.center,
      width: adBanner.size.width.toDouble(),
      height: adBanner.size.height.toDouble(),
      child: AdWidget(ad: adBanner),
    );
  }
}

このスクラップは2022/03/04にクローズされました