Flutter集成Google Ads广告指南
本文档默认已经申请了Google Ads的账号
系统环境
- Mac系统:macOS Big Sur 11.6.1
- Flutter版本:Flutter (Channel stable, 2.5.3, on macOS 11.6.1 20G224 darwin-x64, locale zh-Hans-CN)
注意:Google Ads的广告集成需要科学上网环境
Google Ads申请广告ID
- 使用Google账号登录后开通Ads服务
- 进入Google Ads管理后台创建广告应用
申请广告应用
因为跨平台特性,Android和iOS无法共用一个应用。如果需要同时上架两个平台,需要分别创建两个应用。
输入应用名称即可完成创建。
申请应用下的广告单元
根据需要创建不同类型的广告单元:
- 横幅广告
- 插页广告
- 激励广告
- 原生广告
Flutter项目配置
使用官方插件:google_mobile_ads
- 在pubspec.yaml中添加依赖:
dependencies:google_mobile_ads: ^1.0.1
- 终端执行
flutter pub get
安装依赖
Android项目配置
- 修改android/app/build.gradle,将compileSdkVersion改为31
- 添加Ads服务依赖:
dependencies {implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"implementation 'com.google.android.gms:play-services-ads:20.5.0'
}
- 修改AndroidManifest.xml添加应用ID:
<manifest><application><meta-dataandroid:name="com.google.android.gms.ads.APPLICATION_ID"android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/></application>
</manifest>
iOS项目配置
- 使用Appuploader等iOS开发助手工具准备开发证书和描述文件
- 执行
flutter build ios
或flutter build ios --no-codesign
生成项目 - 打开ios/Runner.xcworkspace文件
- 编辑Info.plist文件,添加以下配置:
<key>GADApplicationIdentifier</key>
<string>ca-app-pub-XXXXXX~XXXXXXXX</string>
<key>SKAdNetworkItems</key>
<array><!-- 此处省略多个SKAdNetworkIdentifier配置 -->
</array>
- 验证配置无误后保存
Flutter项目调用示例
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';void main() {WidgetsFlutterBinding.ensureInitialized();MobileAds.instance.initialize();runApp(MyApp());
}class MyApp extends StatefulWidget { _MyAppState createState() => _MyAppState();
}class _MyAppState extends State<MyApp> {InterstitialAd? _interstitialAd;void initState() {super.initState();_createInterstitialAd();}void _createInterstitialAd() {InterstitialAd.load(adUnitId: InterstitialAd.testAdUnitId,request: AdRequest(),adLoadCallback: InterstitialAdLoadCallback(onAdLoaded: (InterstitialAd ad) {_interstitialAd = ad;},onAdFailedToLoad: (LoadAdError error) {print('InterstitialAd failed to load: $error');},));}void _showInterstitialAd() {if (_interstitialAd != null) {_interstitialAd!.show();}} Widget build(BuildContext context) {return MaterialApp(home: Scaffold(body: Center(child: ElevatedButton(onPressed: _showInterstitialAd,child: Text('显示广告'),),),),);}
}
总结
通过以上步骤,我们完成了Flutter项目中Google Ads的集成。在实际开发中,可以使用Appuploader等工具简化iOS证书管理和打包流程,提高开发效率。广告集成后,建议进行充分测试,确保在不同设备和网络环境下广告能够正常加载和显示。