Flutter Facebook广告集成插件facebook_audience_network的使用

发布于 1周前 作者 wuwangju 来自 Flutter

Flutter Facebook广告集成插件facebook_audience_network的使用

插件介绍

facebook_audience_network 是一个用于在Flutter应用程序中集成Facebook Audience Network广告的插件,支持Android和iOS平台。它提供了多种广告形式,包括横幅广告(Banner Ad)、原生横幅广告(Native Banner Ad)、原生广告(Native Ad)、插屏广告(Interstitial Ad)和激励视频广告(Rewarded Video Ad)。下面将详细介绍如何使用这个插件。

Pub GitHub License Awesome Flutter

广告示例

横幅广告 原生横幅广告 原生广告
Banner Ad Native Banner Ad Native Ad
插屏广告 激励视频广告
Interstitial Ad Rewarded Ad

快速开始

1. 初始化

为了测试目的,你需要获取测试设备的哈希ID。可以通过以下步骤获取:

  1. 在应用初始化时调用 FacebookAudienceNetwork.init()
  2. FacebookBannerAd 小部件放置在你的应用中。
  3. 运行应用,哈希ID会打印到日志中。将其粘贴到 testingId 参数中。
FacebookAudienceNetwork.init(
  testingId: "37b1da9d-b48c-4103-a393-2e095e734bd6", // 可选
  iOSAdvertiserTrackingEnabled: true // 默认为false
);

iOS设置:在Pod文件中,将iOS部署目标版本设置为9.0。在iOS上,支持横幅广告、插屏广告和原生广告。


2. 显示横幅广告

Container(
  alignment: Alignment(0.5, 1),
  child: FacebookBannerAd(
    placementId: Platform.isAndroid ? "YOUR_ANDROID_PLACEMENT_ID" : "YOUR_IOS_PLACEMENT_ID",
    bannerSize: BannerSize.STANDARD,
    listener: (result, value) {
      switch (result) {
        case BannerAdResult.ERROR:
          print("Error: $value");
          break;
        case BannerAdResult.LOADED:
          print("Loaded: $value");
          break;
        case BannerAdResult.CLICKED:
          print("Clicked: $value");
          break;
        case BannerAdResult.LOGGING_IMPRESSION:
          print("Logging Impression: $value");
          break;
      }
    },
  ),
)

3. 显示插屏广告

FacebookInterstitialAd.loadInterstitialAd(
  placementId: "YOUR_PLACEMENT_ID",
  listener: (result, value) {
    if (result == InterstitialAdResult.LOADED)
      FacebookInterstitialAd.showInterstitialAd(delay: 5000);
  },
);

4. 显示激励视频广告(仅限Android)

FacebookRewardedVideoAd.loadRewardedVideoAd(
  placementId: "YOUR_PLACEMENT_ID",
  listener: (result, value) {
    if(result == RewardedVideoResult.LOADED)
      FacebookRewardedVideoAd.showRewardedVideoAd();
    if(result == RewardedVideoResult.VIDEO_COMPLETE)
      print("Video completed");
  },
);

5. 显示原生广告

FacebookNativeAd(
  placementId: "YOUR_PLACEMENT_ID",
  adType: NativeAdType.NATIVE_AD,
  width: double.infinity,
  height: 300,
  backgroundColor: Colors.blue,
  titleColor: Colors.white,
  descriptionColor: Colors.white,
  buttonColor: Colors.deepPurple,
  buttonTitleColor: Colors.white,
  buttonBorderColor: Colors.white,
  keepAlive: true, // 如果你不希望小部件重建时刷新广告视图,请设置为true
  keepExpandedWhileLoading: false, // 如果你希望加载广告时折叠原生广告视图,请设置为false
  expandAnimationDuraion: 300, // 加载广告时展开动画的持续时间(毫秒)
  listener: (result, value) {
    print("Native Ad: $result --> $value");
  },
),

6. 显示原生横幅广告

FacebookNativeAd(
  placementId: "YOUR_PLACEMENT_ID",
  adType: NativeAdType.NATIVE_BANNER_AD,
  bannerAdSize: NativeBannerAdSize.HEIGHT_100,
  width: double.infinity,
  backgroundColor: Colors.blue,
  titleColor: Colors.white,
  descriptionColor: Colors.white,
  buttonColor: Colors.deepPurple,
  buttonTitleColor: Colors.white,
  buttonBorderColor: Colors.white,
  listener: (result, value) {
    print("Native Ad: $result --> $value");
  },
),

示例代码

以下是一个完整的示例代码,展示了如何在Flutter应用中集成并展示不同类型的Facebook广告:

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

void main() => runApp(AdExampleApp());

class AdExampleApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'FB Audience Network Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        buttonTheme: ButtonThemeData(
          textTheme: ButtonTextTheme.primary,
          buttonColor: Colors.blue,
        ),
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text("FB Audience Network Example"),
        ),
        body: AdsPage(),
      ),
    );
  }
}

class AdsPage extends StatefulWidget {
  final String idfa;

  const AdsPage({Key? key, this.idfa = ''}) : super(key: key);

  @override
  AdsPageState createState() => AdsPageState();
}

class AdsPageState extends State<AdsPage> {
  bool _isInterstitialAdLoaded = false;
  bool _isRewardedAdLoaded = false;

  /// 所有广告小部件都存储在这个变量中。当按下按钮时,其相应的广告小部件将被设置为此变量,并通过setState()重新构建视图。
  Widget _currentAd = SizedBox(width: 0.0, height: 0.0);

  @override
  void initState() {
    super.initState();

    /// 请添加你自己的设备测试ID(如果未提供,测试ID将打印到控制台)
    FacebookAudienceNetwork.init(
      testingId: "a77955ee-3304-4635-be65-81029b0f5201",
      iOSAdvertiserTrackingEnabled: true,
    );

    _loadInterstitialAd();
    _loadRewardedVideoAd();
  }

  void _loadInterstitialAd() {
    FacebookInterstitialAd.loadInterstitialAd(
      placementId: "IMG_16_9_APP_INSTALL#2312433698835503_2650502525028617",
      listener: (result, value) {
        print(">> FAN > Interstitial Ad: $result --> $value");
        if (result == InterstitialAdResult.LOADED)
          _isInterstitialAdLoaded = true;

        /// 一旦插屏广告被关闭并失效,通过调用此函数加载新的广告。
        if (result == InterstitialAdResult.DISMISSED && value["invalidated"] == true) {
          _isInterstitialAdLoaded = false;
          _loadInterstitialAd();
        }
      },
    );
  }

  void _loadRewardedVideoAd() {
    FacebookRewardedVideoAd.loadRewardedVideoAd(
      placementId: "YOUR_PLACEMENT_ID",
      listener: (result, value) {
        print("Rewarded Ad: $result --> $value");
        if (result == RewardedVideoAdResult.LOADED) _isRewardedAdLoaded = true;
        if (result == RewardedVideoAdResult.VIDEO_COMPLETE)
          print("Video completed");

        /// 一旦激励视频广告被关闭并失效,通过调用此函数加载新的广告。
        if (result == RewardedVideoAdResult.VIDEO_CLOSED && (value == true || value["invalidated"] == true)) {
          _isRewardedAdLoaded = false;
          _loadRewardedVideoAd();
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Flexible(
          child: Align(
            alignment: Alignment(0, -1.0),
            child: Padding(
              padding: EdgeInsets.all(16),
              child: _getAllButtons(),
            ),
          ),
          fit: FlexFit.tight,
          flex: 2,
        ),
        Flexible(
          child: Align(
            alignment: Alignment(0, 1.0),
            child: _currentAd,
          ),
          fit: FlexFit.tight,
          flex: 3,
        )
      ],
    );
  }

  Widget _getAllButtons() {
    return GridView.count(
      shrinkWrap: true,
      crossAxisCount: 2,
      childAspectRatio: 3,
      children: [
        _getRaisedButton(title: "Banner Ad", onPressed: _showBannerAd),
        _getRaisedButton(title: "Native Ad", onPressed: _showNativeAd),
        _getRaisedButton(title: "Native Banner Ad", onPressed: _showNativeBannerAd),
        _getRaisedButton(title: "Intestitial Ad", onPressed: _showInterstitialAd),
        _getRaisedButton(title: "Rewarded Ad", onPressed: _showRewardedAd),
      ],
    );
  }

  Widget _getRaisedButton({required String title, void Function()? onPressed}) {
    return Padding(
      padding: EdgeInsets.all(8),
      child: ElevatedButton(
        onPressed: onPressed,
        child: Text(
          title,
          textAlign: TextAlign.center,
        ),
      ),
    );
  }

  _showInterstitialAd() {
    if (_isInterstitialAdLoaded)
      FacebookInterstitialAd.showInterstitialAd();
    else
      print("Interstial Ad not yet loaded!");
  }

  _showRewardedAd() {
    if (_isRewardedAdLoaded)
      FacebookRewardedVideoAd.showRewardedVideoAd();
    else
      print("Rewarded Ad not yet loaded!");
  }

  _showBannerAd() {
    setState(() {
      _currentAd = FacebookBannerAd(
        placementId: "IMG_16_9_APP_INSTALL#2312433698835503_2964944860251047", // testid
        bannerSize: BannerSize.STANDARD,
        listener: (result, value) {
          print("Banner Ad: $result --> $value");
        },
      );
    });
  }

  _showNativeBannerAd() {
    setState(() {
      _currentAd = _nativeBannerAd();
    });
  }

  Widget _nativeBannerAd() {
    return FacebookNativeAd(
      placementId: "IMG_16_9_APP_INSTALL#2312433698835503_2964953543583512",
      adType: NativeAdType.NATIVE_BANNER_AD,
      bannerAdSize: NativeBannerAdSize.HEIGHT_100,
      width: double.infinity,
      backgroundColor: Colors.blue,
      titleColor: Colors.white,
      descriptionColor: Colors.white,
      buttonColor: Colors.deepPurple,
      buttonTitleColor: Colors.white,
      buttonBorderColor: Colors.white,
      listener: (result, value) {
        print("Native Banner Ad: $result --> $value");
      },
    );
  }

  _showNativeAd() {
    setState(() {
      _currentAd = _nativeAd();
    });
  }

  Widget _nativeAd() {
    return FacebookNativeAd(
      placementId: "IMG_16_9_APP_INSTALL#2312433698835503_2964952163583650",
      adType: NativeAdType.NATIVE_AD_VERTICAL,
      width: double.infinity,
      height: 300,
      backgroundColor: Colors.blue,
      titleColor: Colors.white,
      descriptionColor: Colors.white,
      buttonColor: Colors.deepPurple,
      buttonTitleColor: Colors.white,
      buttonBorderColor: Colors.white,
      listener: (result, value) {
        print("Native Ad: $result --> $value");
      },
      keepExpandedWhileLoading: true,
      expandAnimationDuraion: 1000,
    );
  }
}

以上就是关于facebook_audience_network插件的详细使用说明及示例代码。希望这些信息能帮助你在Flutter项目中顺利集成Facebook广告。如果你有任何问题或需要进一步的帮助,请随时提问!


更多关于Flutter Facebook广告集成插件facebook_audience_network的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter Facebook广告集成插件facebook_audience_network的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中集成和使用facebook_audience_network插件来展示Facebook广告的示例代码。这个示例将展示如何初始化插件并展示一个横幅广告(Banner Ad)。

第一步:添加依赖

首先,在你的pubspec.yaml文件中添加facebook_audience_network插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  facebook_audience_network: ^x.y.z  # 请使用最新版本号

第二步:配置Android项目

  1. android/app/src/main/AndroidManifest.xml中添加必要的权限和配置
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <!-- 其他配置 -->

    <application
        android:name=".MyApplication"
        <!-- 其他配置 -->
    >
        <!-- Facebook Audience Network配置 -->
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />
        <activity
            android:name="com.facebook.ads.AudienceNetworkActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />
    </application>

    <!-- 其他配置 -->

</manifest>

注意:确保你已经在strings.xml文件中定义了facebook_app_id

  1. android/app/build.gradle中添加Facebook SDK的依赖
dependencies {
    implementation 'com.facebook.android:audience-network-sdk:x.y.z'  // 请使用最新版本号
}

第三步:配置iOS项目

  1. ios/Runner/Info.plist中添加Facebook的配置
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>fbYOUR_FACEBOOK_APP_ID</string> <!-- 替换为你的Facebook应用ID -->
        </array>
    </dict>
</array>
<key>FacebookAppID</key>
<string>YOUR_FACEBOOK_APP_ID</string> <!-- 替换为你的Facebook应用ID -->
<key>FacebookDisplayName</key>
<string>YourAppName</string> <!-- 替换为你的应用名称 -->
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>fbapi</string>
    <string>fb-messenger-share-api</string>
    <string>fbauth2</string>
    <string>fbshareextension</string>
</array>
  1. ios/Podfile中添加Facebook SDK的依赖(如果未自动添加):
pod 'FBAudienceNetwork', '~> x.y.z'  # 请使用最新版本号

然后运行pod install

第四步:在Flutter代码中集成广告

  1. 初始化插件

在你的main.dart或其他合适的Dart文件中,初始化FacebookAudienceNetwork插件。

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Facebook Audience Network Example'),
        ),
        body: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  BannerAd _bannerAd;

  @override
  void initState() {
    super.initState();
    _loadBannerAd();
  }

  void _loadBannerAd() {
    // 替换为你的广告位ID和测试设备ID(如果有)
    final String placementId = "YOUR_PLACEMENT_ID";
    final BannerAdSize size = BannerAdSize.BANNER_HEIGHT_50;
    
    _bannerAd = BannerAd(
      placementId: placementId,
      adSize: size,
      adListener: BannerAdListener(
        onError: (error) {
          print("Banner ad error: $error");
        },
        onAdLoaded: () {
          print("Banner ad loaded");
          // 这里可以更新UI以显示广告
        },
        onAdClicked: () {
          print("Banner ad clicked");
        },
        onLoggingImpression: () {
          print("Banner ad impression logged");
        },
      ),
    );

    _bannerAd.load();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: _bannerAd?.widget ?? Container(),
    );
  }

  @override
  void dispose() {
    _bannerAd?.dispose();
    super.dispose();
  }
}

注意事项

  1. 测试广告:在开发阶段,使用Facebook提供的测试广告位ID和测试设备ID来确保广告能够正确加载。
  2. 广告政策:确保你的应用符合Facebook的广告政策。
  3. 隐私政策:确保你的应用有适当的隐私政策,并且用户同意收集和使用他们的数据来展示广告。

希望这个示例代码能帮助你在Flutter项目中集成和使用Facebook广告。

回到顶部