我正在努力寻找代码中的错误。我遵循本教程在我的flutter应用程序中实现admob。https://codelabs.developers.google.com/codelabs/admob-ads-in-flutter # 7
我添加了android manifest和infoplist。我还在main.dart中初始化了移动广告。
实现代码:
class _NotesRouteState extends State<NotesRoute> {
InterstitialAd? _interstitialAd;
bool _isInterstitialAdReady = false;
void initState() {
super.initState();
_loadInterstitialAd();
}
void _loadInterstitialAd() {
InterstitialAd.load(
adUnitId: AdHelper.interstitialAdUnitId,
request: AdRequest(),
adLoadCallback: InterstitialAdLoadCallback(
onAdLoaded: (ad) {
this._interstitialAd = ad;
ad.fullScreenContentCallback = FullScreenContentCallback(
onAdDismissedFullScreenContent: (ad) {
print('$ad onAdDismissedFullScreenContent.');
ad.dispose();
},
);
_isInterstitialAdReady = true;
},
onAdFailedToLoad: (err) {
print('Failed to load an interstitial ad: ${err.message}');
_isInterstitialAdReady = false;
},
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
top: false,
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Align(
alignment: Alignment.topLeft,
child: Text(
'General Subjects',
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
color: Colors.lightBlue,
),
),
),
),
MyButton(
onTap: () {
if (_isInterstitialAdReady) {
_interstitialAd?.show();
} else {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => BahasaRoute()),
);
}
},
],
),
),
);
}
}
希望从你们那里得到一些指导。谢谢!
_isInterstitialAdReady = true
未被设置为setState。移除开关中的状态检查,它应该可以工作,或者在状态检查之前添加一个setState()
。