[Flutter] admob Banner 광고(AlertDialog)

2024. 4. 4. 14:42dev/flutter

728x90
반응형

하단 광고는 Scaffold의 bottomNavigationBar에 Visibility로 load가 끝나서 광고가 생긴 경우에 setState상태관리로 보여지도록 한다.

 

[라이브러리 불러오기]

add

flutter pub add google_mobile_ads

 

 

[AppId등록]

- android

<manifest>
    <application>
        <!-- Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713 -->
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>
    <application>
<manifest>

 

- iOS

ios/Runner/Info.plist

<key>GADApplicationIdentifier</key>
<string>ca-app-pub-################~##########</string>

 

 

[사용]

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  MobileAds.instance.initialize();

  runApp(MyApp());
}

 

 

[광고 객체 불러오기]

: 광고 위젯이 광고 객체보다 먼저 호출되면 안됨 - 광고 객체가 'load'를 먼저 해야한다.

  static const _insets = 16.0;
  AdManagerBannerAd? _inlineAdaptiveAd;
  bool _isLoaded = false;
  AdSize? _adSize;
  late Orientation _currentOrientation;

  double get _adWidth => MediaQuery.of(context).size.width - (2 * _insets);

 

위의 코드는 전체화면에 광고를 보여주는 경우에 해당하며,

나는 나가기시 AlertDialog에 적용하려함

 

adWidth라는 double타입의 프로퍼티를 생성하고,

AlertDialog에서 LayoutBuilder를 사용하여 크기 값을 가져온다.

double adWidth = 232;


return AlertDialog(
  content: LayoutBuilder(
    builder: (context, constraints) {
      adWidth = constraints.maxWidth;
      
      return SingleChildView(
        child: ..
      )
    }
  )
)

 

 

아직 광고 위젯을 불러올 차례가 아닌 load를 해야한다.

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _currentOrientation = MediaQuery.of(context).orientation;
    _loadAd();
  }
  void _loadAd() async {
    await _inlineAdaptiveAd?.dispose();
    setState(() {
      _inlineAdaptiveAd = null;
      _isLoaded = false;
    });

    // Get an inline adaptive size for the current orientation.
    AdSize size = AdSize.getCurrentOrientationInlineAdaptiveBannerAdSize(
        _adWidth.truncate());

    _inlineAdaptiveAd = AdManagerBannerAd(
      adUnitId: '/6499/example/banner',
      sizes: [size],
      request: AdManagerAdRequest(),
      listener: AdManagerBannerAdListener(
        onAdLoaded: (Ad ad) async {
          print('Inline adaptive banner loaded: ${ad.responseInfo}');

          // After the ad is loaded, get the platform ad size and use it to
          // update the height of the container. This is necessary because the
          // height can change after the ad is loaded.
          AdManagerBannerAd bannerAd = (ad as AdManagerBannerAd);
          final AdSize? size = await bannerAd.getPlatformAdSize();
          if (size == null) {
            print('Error: getPlatformAdSize() returned null for $bannerAd');
            return;
          }

          setState(() {
            _inlineAdaptiveAd = bannerAd;
            _isLoaded = true;
            _adSize = size;
          });
        },
        onAdFailedToLoad: (Ad ad, LoadAdError error) {
          print('Inline adaptive banner failedToLoad: $error');
          ad.dispose();
        },
      ),
    );
    await _inlineAdaptiveAd!.load();
  }

 

 

이렇게 _inlineAdaptiveAd객체가 load가 되도록하고,

build에서 AlertDialog를 사용하고, 그 안에 AdWidget을 넣어주자.

 

[광고 위젯 만들기]

inlineAdaptiveAd객체가 null인 경우 SizedBox를 넣어준다.

return isLoaded
  ? AdWidget(ad: _inlineAdaptiveAd!)
  : const SizedBox()

 

 

[참고]

inline Banner : https://github.com/googleads/googleads-mobile-flutter/blob/main/packages/google_mobile_ads/example/lib/inline_adaptive_example.dart

728x90
반응형

'dev > flutter' 카테고리의 다른 글

[dart] covariant  (0) 2024.04.29
[Flutter] Filled #shape #buttonstyle  (0) 2024.04.24
[Flutter] Backpressed WillPopScope #pop  (0) 2024.04.03
[Flutter] Dropdown #Spinner  (0) 2024.03.29
[Flutter] AnimatedList  (0) 2024.03.06