天天看點

Flutter接入FirebaseAdmob

1、建立Firebase賬号,并建立項目,在新建立的項目裡添加Android、iOS工程,在iOS項目裡下載下傳GoogleService-info.plist

2、建立Admob賬号,并分别建立Android、iOS對應工程,并分别建立所需廣告,如bannerAD橫幅廣告,并分别記錄Android、iOS對應的項目ID及廣告ID

3、Flutter工程添加Firebase_admob依賴

dependencies:
  firebase_admob: ^0.9.0+10
           

4、Android工程在Application節點下添加meta-data

<meta-data
    android:name="com.google.android.gms.ads.APPLICATION_ID"
    android:value="[ADMOB_APP_ID]"/>
           

 5、iOS工程Info.plist添加鍵值對

<key>GADApplicationIdentifier</key>
<string>[ADMOB_APP_ID]</string>
           

6、初始化Admob

FirebaseAdMob.instance.initialize(appId: appId);
           

7、添加廣告,banner廣告為例

MobileAdTargetingInfo targetingInfo = MobileAdTargetingInfo(
  keywords: <String>['flutterio', 'beautiful apps'],
  contentUrl: 'https://flutter.io',
  birthday: DateTime.now(),
  childDirected: false,
  designedForFamilies: false,
  gender: MobileAdGender.male, // or MobileAdGender.female, MobileAdGender.unknown
  testDevices: <String>[], // Android emulators are considered test devices
);
BannerAd myBanner = BannerAd(
  // Replace the testAdUnitId with an ad unit id from the AdMob dash.
  // https://developers.google.com/admob/android/test-ads
  // https://developers.google.com/admob/ios/test-ads
  adUnitId: BannerAd.testAdUnitId,
  size: AdSize.smartBanner,
  targetingInfo: targetingInfo,
  listener: (MobileAdEvent event) {
    print("BannerAd event is $event");
  },
);
myBanner
  // typically this happens well before the ad is shown
  ..load()
  ..show(
    // Positions the banner ad 60 pixels from the bottom of the screen
    anchorOffset: 60.0,
    // Positions the banner ad 10 pixels from the center of the screen to the right
    horizontalCenterOffset: 10.0,
    // Banner Position
    anchorType: AnchorType.bottom,
  );
           

 注意:

1、Admob推送廣告 需先設定付款資訊 完成設定或添加廣告後可能需要等待幾小時 才能正常看到廣告 不想等待的話 可使用測試廣告ID測試

2、真機上可能需要在testDevices添加真機ID,否則可能擷取廣告失敗,真機ID在進行測試時控制台輸出