如何在Flutter应用的底部导航栏中展示Unity Banner广告
以下是实现将Unity Banner广告与底部导航栏一同展示的完整代码示例:
1. 添加依赖
在pubspec.yaml中引入Unity Ads插件:
dependencies: flutter: sdk: flutter unity_ads_plugin: ^0.6.0
执行flutter pub get完成依赖安装。
2. 完整实现代码
import 'package:flutter/material.dart'; import 'package:unity_ads_plugin/unity_ads_plugin.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Unity Banner Demo', theme: ThemeData(primarySwatch: Colors.blue), home: const HomePage(), ); } } class HomePage extends StatefulWidget { const HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { // 替换为你在Unity Ads后台获取的Game ID final String _unityGameId = 'YOUR_GAME_ID'; // 替换为你的Banner广告单元ID final String _bannerAdUnitId = 'YOUR_BANNER_AD_UNIT_ID'; @override void initState() { super.initState(); _initUnityAds(); } void _initUnityAds() async { await UnityAds.init( gameId: _unityGameId, testMode: true, // 测试阶段开启,发布时改为false onComplete: () => debugPrint('Unity Ads初始化成功'), onFailed: (error, msg) => debugPrint('Unity Ads初始化失败: $error - $msg'), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('应用主页')), body: const Center(child: Text('应用内容展示区')), // 底部组合:Banner广告 + 导航栏 bottomNavigationBar: Column( mainAxisSize: MainAxisSize.min, children: [ // Unity Banner广告组件 UnityBannerAd( placementId: _bannerAdUnitId, onLoad: () => debugPrint('Banner广告加载完成'), onClick: () => debugPrint('Banner广告被点击'), onFailed: (error, msg) => debugPrint('Banner加载失败: $error - $msg'), ), // 底部导航栏 BottomNavigationBar( items: const [ BottomNavigationBarItem(icon: Icon(Icons.home), label: '首页'), BottomNavigationBarItem(icon: Icons.person, label: '我的'), ], currentIndex: 0, onTap: (index) => debugPrint('切换到页面 $index'), ), ], ), ); } }
关键注意事项
- 务必替换代码中的
YOUR_GAME_ID和YOUR_BANNER_AD_UNIT_ID为Unity Ads后台生成的真实ID testMode参数在正式发布前要改为false,否则只会展示测试广告- Android端需确保
AndroidManifest.xml中添加了INTERNET权限;iOS端需在Info.plist中配置App Transport Security(允许HTTP请求,或添加Unity Ads的域名例外) - 如果需要将Banner广告放在导航栏上方,调整
Column中UnityBannerAd和BottomNavigationBar的顺序即可
内容的提问来源于stack exchange,提问作者Albert Tetteh Adjei
相关产品推荐
相关产品推荐

