Flutter Web禁用AdMob遇白屏及MissingPluginException问题求助
问题情况
我开发的Flutter应用同时支持Web和移动端,集成了AdMob横幅广告。因为google_mobile_ads不支持Web平台,我用条件导入的方式只在移动端初始化广告,但在Chrome中运行时应用卡在白屏,控制台抛出错误:
Error: MissingPluginException(No implementation found for method _init on channel plugins.flutter.io/google_mobile_ads)
现有代码
export.dart
export 'ad_mobile.dart' if (dart.library.html) 'ad_web.dart';
ad_mobile.dart
import 'package:google_mobile_ads/google_mobile_ads.dart'; Future<dynamic> initAds() async { await _initGoogleMobileAds(); } Future<InitializationStatus> _initGoogleMobileAds() { RequestConfiguration configuration = RequestConfiguration( testDeviceIds: <String>[ testDeviceId, ], ); MobileAds.instance.updateRequestConfiguration(configuration); return MobileAds.instance.initialize(); }
ad_web.dart
import 'dart:developer'; Future initAds() async { log('ADS DOES\'NT SUPPORTED FOR WEB PLATFORMS'); }
问题根源
条件导入只是切换了对外暴露的初始化方法,但google_mobile_ads的依赖代码仍然会被Web端编译打包,导致运行时尝试调用原生插件通道方法,而Web端根本没有对应的实现,从而抛出异常。
解决步骤
隔离移动端广告代码
确保所有涉及google_mobile_ads的代码(包括类型、方法调用)都只存在于移动端专属文件中,Web端的代码完全不碰这个包的任何内容。限制依赖的平台范围
在pubspec.yaml中给google_mobile_ads添加平台限制,让它只在Android和iOS上生效:
dependencies: google_mobile_ads: ^2.4.0 # 替换成你使用的版本 platform: android: true ios: true web: false
检查全局代码引用
排查应用入口、全局状态管理等地方,确保没有直接引入google_mobile_ads的代码,所有广告相关操作都通过export.dart暴露的统一接口调用。清理重建项目
执行以下命令清理缓存并重新构建:
flutter clean flutter pub get flutter run -d chrome
补充提示
如果你的UI中有广告展示组件,也要用同样的条件导入逻辑:移动端渲染AdMob横幅,Web端要么显示占位组件,要么直接隐藏广告区域,避免Web端加载到移动端的广告组件代码。
内容的提问来源于stack exchange,提问作者Turan Aktas

