본문 바로가기
게임 & 프로그래밍

Admob for Flutter 플러터에 구글 애드몹 광고 달기

by 장미제이 2021. 10. 28.
반응형

앱을 만드는 이유는 여러가지가 있겠지만....

 

소소하게 커피값이라도 벌 수 있다면 금상첨화일 것이다.

 

앱을 통해 수익을 얻는 방법은 여러가지가 있을 수 있지만...

 

가장 간단한 것이 광고를 통한 수익일 것이다.

 

여기서는 플러터로 만든 앱에 구글 애드몹 배너를 붙이는 방법을 알아볼 것이다.

 

방법은 아주 간단하지만  먼저 애드몹에 가입하고 광고단위를 생성하는 것이 선행되어야 한다.

 

아직 구글 애드몹 계정이 없다면 https://admob.google.com/home/ 을 방문하여 계정을 만들고 광고단위를 등록하자.

 

선행 작업을 모두 마쳤다면

 

플러터 앱 개발이 그렇듯 애드몹을 추가할 수있는 패키지를 추가해 주어야 한다.

 

패키지에 대한 자세한 설명은 아래 사이트를 방문해 알아보자.

  https://pub.dev/packages/google_mobile_ads

 

google_mobile_ads | Flutter Package

Flutter plugin for Google Mobile Ads, supporting banner, interstitial (full-screen), rewarded and native ads

pub.dev

 

1. 아래와 같이 pubspec.yaml  에 패키지를 추가 합니다.

dependencies:
  google_mobile_ads: ^0.13.5

 

2. 애드몹 초기화 코드를 작성.   그냥 묻지도 따지지도 말고 따라하기^^

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  MobileAds.instance.initialize();
  
  ....

 

여기선 가장 기본이되고 앱 사용자에게 거부감이 가장 적은 배너 광고를 먼저 추가해보자.

class _BottomNavScreenState extends State<BottomNavScreen> {
  
  static final AdRequest request = AdRequest(
    keywords: <String>['foo', 'bar'],
    contentUrl: 'http://foo.com/bar.html',
    nonPersonalizedAds: true,
  );
  
  BannerAd? _anchoredBanner;
  bool _loadingAnchoredBanner = false;
  
  @override
  void initState() {
    super.initState();
  }


  Future<void> _createAnchoredBanner(BuildContext context) async {
    final AnchoredAdaptiveBannerAdSize? size =
        await AdSize.getAnchoredAdaptiveBannerAdSize(
      Orientation.portrait,
      MediaQuery.of(context).size.width.truncate(),
    );

    if (size == null) {
      print('Unable to get height of anchored banner.');
      return;
    }

    final BannerAd banner = BannerAd(
      size: size,
      request: request,
      adUnitId:
          Platform.isAndroid ? 'ca-app-pub-5776739179947162/1504334615' : '',
      listener: BannerAdListener(
        onAdLoaded: (Ad ad) {
          print('$BannerAd loaded.');
          setState(() {
            _anchoredBanner = ad as BannerAd?;
          });
        },
        onAdFailedToLoad: (Ad ad, LoadAdError error) {
          print('$BannerAd failedToLoad: $error');
          ad.dispose();
        },
        onAdOpened: (Ad ad) => print('$BannerAd onAdOpened.'),
        onAdClosed: (Ad ad) => print('$BannerAd onAdClosed.'),
      ),
    );
    return banner.load();
  }
  
    @override
  Widget build(BuildContext context) {
    if (!_loadingAnchoredBanner) {
      _loadingAnchoredBanner = true;
      _createAnchoredBanner(context);
    }

    return Scaffold(
      body: Stack(
        alignment: AlignmentDirectional.bottomCenter,
        children: <Widget>[
          _screens[_currentIndex],
          if (_anchoredBanner != null)
            Container(
              color: Colors.green,
              width: _anchoredBanner!.size.width.toDouble(),
              height: _anchoredBanner!.size.height.toDouble(),
              child: AdWidget(ad: _anchoredBanner!),
            ),
        ],
      ),
      
      ......
      
  }

 

모든 작업이 완료되면 아래와 같이 테스트 광고가 노출된다.

 

스토어에 배포가되면 "Test Ad" 가 없어지고 실제 클릭시 수익이 발생하는 광고가 된다.

 

기존 자바나, 코틀린으로 개발하는 과정보다 단순하고 쉽다.

댓글