Flutter广告集成插件functional_google_mobile_ads的使用

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

Flutter广告集成插件functional_google_mobile_ads的使用

引言

本项目是 google_mobile_ads 的功能版本。

首先,你需要遵循移动广告SDK(快速入门)

从这里开始

导入

import 'package:functional_google_mobile_ads/functional_google_mobile_ads.dart';

一行功能用法

FunctionalInterstitialAd

await FunctionalInterstitialAd.loadAndShow(adUnitId: 'adUnitId');

FunctionalRewardedAd

await FunctionalRewardedAd.loadAndShow(adUnitId: 'adUnitId');

FunctionalRewardedInterstitialAd

await FunctionalRewardedInterstitialAd.loadAndShow(adUnitId: 'adUnitId');

FunctionalBannerAd

Column(
    children: [
        FunctionalBannerAd(adUnitId: 'adUnitId', adSize: AdSize.banner),
    ] 
)

高级用法

final ad = FunctionalRewardedAd();
try {
  await ad.load(adUnitId: 'adUnitId');
  final item = await ad.show();
  print('rewarded item: $item');
} catch (error) {
  print(error);
} finally {
  ad.dispose();
}

完整示例代码

以下是一个完整的示例代码,展示了如何在Flutter应用中使用 functional_google_mobile_ads 插件来集成各种类型的广告。

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  MobileAds.instance.initialize();
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _rewarded = FunctionalRewardedAd();

  [@override](/user/override)
  void initState() {
    super.initState();
  }

  [@override](/user/override)
  void dispose() {
    super.dispose();
    _rewarded.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Functional Google Mobile Ads 示例'),
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            ElevatedButton(
                onPressed: () async {
                  await FunctionalInterstitialAd.loadAndShow(
                      adUnitId: 'ca-app-pub-3940256099942544/1033173712');

                  print('插屏广告加载成功');
                },
                child: const Text('插屏广告')),
            ElevatedButton(
                onPressed: () async {
                  final item = await FunctionalRewardedAd.loadAndShow(
                      adUnitId: 'ca-app-pub-3940256099942544/5224354917');

                  print('奖励物品数量: ${item?.amount}');
                  print('奖励物品类型: ${item?.type}');
                },
                child: const Text('激励视频广告')),
            ElevatedButton(
                onPressed: () async {
                  final item = await FunctionalRewardedInterstitialAd.loadAndShow(
                      adUnitId: 'ca-app-pub-3940256099942544/5354046379');

                  print('奖励物品数量: ${item?.amount}');
                  print('奖励物品类型: ${item?.type}');
                },
                child: const Text('激励插屏广告')),
            const Spacer(),
            FunctionalBannerAd(
              adUnitId: 'ca-app-pub-3940256099942544/6300978111',
              adSize: AdSize.banner,
            ),
          ],
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是一个关于如何在Flutter应用中集成并使用functional_google_mobile_ads插件的代码示例。这个插件允许你在Flutter应用中显示Google Mobile Ads(例如横幅广告、插屏广告和奖励视频广告)。

首先,确保你已经在pubspec.yaml文件中添加了functional_google_mobile_ads依赖:

dependencies:
  flutter:
    sdk: flutter
  functional_google_mobile_ads: ^x.y.z  # 请替换为最新版本号

然后运行flutter pub get来安装依赖。

接下来,按照以下步骤配置和显示广告。

1. 初始化Mobile Ads SDK

在你的Flutter应用的入口点(通常是main.dart),初始化Mobile Ads SDK:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

2. 配置AdUnit

在你的应用中配置一个AdUnit。例如,为横幅广告配置一个AdUnit:

final BannerAd myBanner = BannerAd(
  adUnitId: 'ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx', // 替换为你的AdUnit ID
  size: AdSize.banner,
  request: AdRequest(
    keywords: <String>['flutter', 'mobile ads'],
    contentUrl: 'https://www.example.com',
    nonPersonalizedAdsOnly: false, // 如果只想显示非个性化广告,设置为true
  ),
  listener: BannerAdListener(
    onAdLoaded: () {
      print('Banner Ad loaded.');
    },
    onAdFailedToLoad: (AdLoadError error) {
      print('Banner Ad failed to load: ${error.message}');
      myBanner.dispose();
    },
    onAdOpened: () {
      print('Banner Ad opened.');
    },
    onAdClosed: () {
      print('Banner Ad closed.');
      myBanner.dispose();
    },
  ),
);

3. 显示横幅广告

在你的页面或组件中显示横幅广告:

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

class _MyHomePageState extends State<MyHomePage> {
  BannerAd? _myBanner;

  @override
  void initState() {
    super.initState();
    _myBanner = myBanner; // 使用之前定义的BannerAd实例
    _myBanner!.load();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Functional Google Mobile Ads Example'),
      ),
      body: Center(
        child: _myBanner!.adWidget ?? Container(),
      ),
    );
  }

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

4. 处理其他类型的广告(如插屏广告和奖励视频广告)

类似地,你可以创建和显示插屏广告和奖励视频广告。以下是一个插屏广告的示例:

final InterstitialAd myInterstitial = InterstitialAd(
  adUnitId: 'ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx', // 替换为你的AdUnit ID
  request: AdRequest(),
  listener: InterstitialAdListener(
    onAdLoaded: () {
      myInterstitial.show();
    },
    onAdFailedToLoad: (AdLoadError error) {
      print('Interstitial Ad failed to load: ${error.message}');
      myInterstitial.dispose();
    },
    onAdOpened: () {
      print('Interstitial Ad opened.');
    },
    onAdClosed: () {
      print('Interstitial Ad closed.');
      myInterstitial.dispose();
    },
  ),
);

在合适的时机加载并显示插屏广告,例如在按钮点击事件中:

ElevatedButton(
  onPressed: () {
    myInterstitial.load();
  },
  child: Text('Show Interstitial Ad'),
),

请注意,这些代码示例需要在实际应用中替换为真实的AdUnit ID,并且可能需要根据你的应用需求进行进一步调整。此外,确保你已经按照Google Mobile Ads的要求在Google AdMob控制台中正确设置了你的应用。

回到顶部