반응형

애드몹(Admob) 연동 전 준비

  • 아래 링크 참고하여 진행 광고 단위 추가
  • 해당 과정에서 만든 광고ID와 광고단위ID를 아래에서 사용함.

dependencies

dependencies:
  google_mobile_ads: ^4.0.0 # 추가

AndroidManifests.xml

경로 : android/app/src/main/AndroidManifest.xml

<application>
    <meta-data
        android:name="com.google.android.gms.ads.APPLICATION_ID"
        android:value="{광고_ID_입력}" 
    />
</application>

multidex 설정

경로 : android/app/build.gradle

android {
    defaultConfig {
        multiDexEnabled true // 추가
    }
}

위 설정을 하지 않으면 앱 빌드 및 실행시 아래 오류가 발생함.
해당 오류가 발생하지 않는다면 위 설정은 패스해도 됨.

[!] App requires Multidex support
    Multidex support is required for your android app to build since the number of methods has exceeded 64k. See https://docs.flutter.dev/deployment/android#enabling-multidex-support for more information. You may pass the --no-multidex flag to skip Flutter's multidex support to use a manual solution.

main.dart

import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

import 'BannerAdWidget.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  MobileAds.instance.initialize();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    MediaQueryData mediaQueryData = MediaQuery.of(context);
    double width = mediaQueryData.size.width;
    double height = 50;

    return MaterialApp(
      title: 'Admob Demo',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Admob Demo'),
        ),
        body: Center(
          child: BannerAdWidget(
            adUnitId: "{광고_단위_ID_입력}", // 테스트시에는 오른쪽 광고 단위 ID 입력 : ca-app-pub-3940256099942544/9214589741
            width: width,
            height: height,
          ),
        ),
      ),
    );
  }
}

BannerAdWidget.dart

import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

class BannerAdWidget extends StatefulWidget {
  final double width;
  final double height;
  final String adUnitId;

  const BannerAdWidget({
    super.key,
    required this.width,
    required this.height,
    required this.adUnitId,
  });

  @override
  State<BannerAdWidget> createState() => _BannerAdWidgetState(
        width: width,
        height: height,
        adUnitId: adUnitId,
      );
}

class _BannerAdWidgetState extends State<BannerAdWidget> with WidgetsBindingObserver {
  final double width;
  final double height;
  final String adUnitId;

  BannerAd? _bannerAd;

  _BannerAdWidgetState({
    required this.width,
    required this.height,
    required this.adUnitId,
  });

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _loadAd();
  }

  @override
  void dispose() {
    _bannerAd?.dispose();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      _loadAd();
    }
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox( // SizedBox 같은거로 영역을 제한하지 않으면 오류 발생할 수 있음
      width: width,
      height: height,
      child: _bannerAd != null ? AdWidget(ad: _bannerAd!) : const Text(''),
    );
  }

  void _loadAd() {
    setState(() {
      _bannerAd = null;
    });

    BannerAd(
      adUnitId: adUnitId,
      request: const AdRequest(),
      size: AdSize(
        width: width.toInt(),
        height: height.toInt(),
      ),
      listener: BannerAdListener(
        onAdLoaded: (ad) {
          setState(() {
            _bannerAd = ad as BannerAd;
          });
        },
        onAdFailedToLoad: (ad, err) {
          ad.dispose();
        },
        onAdOpened: (Ad ad) {},
        onAdClosed: (Ad ad) {},
        onAdImpression: (Ad ad) {},
      ),
    ).load();
  }
}

화면

참고

반응형

'Development > Flutter' 카테고리의 다른 글

[Flutter] Provider  (0) 2024.04.16
[Flutter] 안드로이드 릴리즈 빌드하기(.aab)  (0) 2024.03.24
[Flutter] Http  (0) 2024.03.03
[Flutter] TextField  (0) 2024.02.23
[Flutter] StatefulWidget  (0) 2024.02.23

+ Recent posts