2020-04-24

【Flutter】設定放送橫幅廣告(本套件已停止開發)

目前可以搜尋到 2 個支援 Flutter 放送 AdMob 的套件,其中 firebase_admob 看似是官方出的套件,目前是 0.9.3+2 版。

老人家沒有 Mac,所以只能試作 Android app


先建立一個 Flutter 專案



選擇 Flutter Application(圖略)


輸入專案名稱Flutter SDK 的路徑,及存放專案的位置
在本例,我的 Flutter 是安裝在 D:\flutter






再來就採用預設值,直接按 下一步


展開專案,找到 pubspec.yaml,並打開檔案


pubspec.yaml
  1.  
  2. ...
  3. ...
  4.  
  5. dependencies:
  6. ...
  7. ...
  8.  
  9. cupertino_icons: ^0.1.2
  10.  
  11. # admob, 注意:要跟上面對齊(感覺有類似 Python 的強制編排)
  12. firebase_admob: ^0.9.3+2
  13.  
  14. ...
  15. ...
  16.  



找到並編輯 AndroidManifest.xml

  1.  
  2. ...
  3. ...
  4. <application
  5. ...
  6. ... >
  7.  
  8. <meta-data
  9. android:name="com.google.android.gms.ads.APPLICATION_ID"
  10. android:value="ca-app-pub-3940256099942544~3347511713"/> 測試用的 app-ID, 將來正式上線時再換成您的 app-ID
  11.  
  12. ...
  13. ...
  14.  


切換到 main.dart 頁籤
  1.  
  2. import 'dart:io';
  3. import 'package:flutter/material.dart';
  4. import 'package:firebase_admob/firebase_admob.dart'; // 主要加入這列
  5.  
  6. const String testDevice = 'ASUS Z017DA';
  7.  
  8. ...
  9. ...
  10.  
  11. class _MyHomePageState extends State<myhomepage> {
  12. int _counter = 0;
  13.  
  14. // 加入這段
  15. static const MobileAdTargetingInfo targetingInfo = MobileAdTargetingInfo(
  16. testDevices: testDevice != null ? <string>[testDevice] : null,
  17. keywords: <string>['foo', 'bar'],
  18. contentUrl: 'http://foo.com/bar.html',
  19. childDirected: true,
  20. nonPersonalizedAds: true,
  21. );
  22.  
  23. BannerAd _bannerAd;
  24.  
  25. BannerAd createBannerAd() {
  26. return BannerAd(
  27. adUnitId: BannerAd.testAdUnitId, // 測試時用的 unit ID
  28. // adUnitId: "正式的橫幅 unit ID",
  29. // size: AdSize.banner, // 一般型, 320*50
  30. size: AdSize.smartBanner, // 智慧型, 468*60
  31. // size: AdSize.mediumRectangle, // 中矩型, 300*250
  32. // size: AdSize.largeBanner, // 大型橫幅, 320*100
  33. // size: AdSize.fullBanner, // 468*60
  34. targetingInfo: targetingInfo,
  35. listener: (MobileAdEvent event) {
  36. print("BannerAd event $event");
  37. },
  38. );
  39. }
  40.  
  41. @override
  42. void initState()
  43. {
  44. super.initState();
  45. FirebaseAdMob.instance.initialize(appId: FirebaseAdMob.testAppId);
  46. _bannerAd = createBannerAd()..load()
  47. ..show();
  48. }
  49.  
  50. @override
  51. void dispose()
  52. {
  53. _bannerAd?.dispose();
  54. super.dispose();
  55. }
  56.  
  57. ...
  58. ...
  59.  


app 執行畫面



沒有留言:

張貼留言