如何在Flutter中用PageView加载谷歌广告



我使用google_mobile_ads: ^0.12.1+1在我的应用程序中显示广告。除了体内有PageViewScaffold bottomNavigationBar,它在所有地方都能正常工作。相关代码为-

class QuizPage extends StatefulWidget {
final List<Question> questions;
QuizPage({Key key, this.questions}) : super(key: key);
@override
_QuizPageState createState() => _QuizPageState();
}
class _QuizPageState extends State<QuizPage> {
PageController controller;
Question question;
int currentPage = 0;
@override
void initState() {
super.initState();
controller = PageController();
question = widget.questions.first;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Title'),
),
body: buildQuestionsBody(),
bottomNavigationBar: loadAds(),
);
}
Widget buildQuestionsBody() {
return PageView.builder(
onPageChanged: (index) => nextQuestion(index: index),
controller: controller,
itemCount: widget.questions.length,
itemBuilder: (context, index) {
return Container(
child: Center(
child: Text(
widget.questions[index].questionText,
textAlign: TextAlign.center,
)),
);
},
);
}
Widget loadAds() {
return Container(
height: 50,
child: AdWidget(
key: UniqueKey(),
ad: AdMobService.createBannerAd()..load(),
),
);
}
void nextQuestion({int index, bool jump = false}) {
final nextPage = controller.page + 1;
final indexPage = index ?? nextPage.toInt();
setState(() {
question = widget.questions[indexPage];
currentPage = indexPage;
});
if (jump) {
controller.jumpToPage(indexPage);
}
}
}

如果我这样运行上面的代码,或者将controller = PageController();initState移到我声明变量的顶部,广告最初会加载,但在更改页面时不会加载,应用程序也会冻结,不会出现任何错误。

如果我从initState中删除controller = PageController();,广告会正常加载,而且在滑动页面时也会发生变化,但现在我收到一个错误-getter‘page’在null时被调用

我找不出错误的根源。

编辑1-经过多次尝试,我发现每当调用setState()时都会发生此冲突,例如每当我在该代码中调用nextQuestion或调用setState()的其他方法时。如果没有谷歌广告,setState在所有方法中都能很好地工作。所以现在的问题应该是-如何让谷歌广告与setState((一起工作

我尝试过这种方法,它能在中工作

class QuizPage extends StatefulWidget {
final List<Question> questions;
QuizPage({Key key, @required this.questions}) : super(key: key);
@override
_QuizPageState createState() => _QuizPageState();
}
class _QuizPageState extends State<QuizPage> {
PageController _controller=PageController();
List<Widget> _questions;
@override
void initState() {
super.initState();
if(widget.questions==null)
_questions = <Widget>[Text("Alas! No questions RN")];
else{
_questions = widget.questions.map((e)=>Container(
child: Center(
child: Text(
e.questionText,
textAlign: TextAlign.center,
)),
))
.toList();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: Appbar(
title: Text('Title'),
),
body: buildQuestionsBody(),
bottomNavigationBar: loadAds(),
);
}
Widget buildQuestionsBody() {
return PageView(
controller: _controller,
children: _questions);
}
Widget loadAds() {
return Container(
height: 50,
child: AdWidget(
key: UniqueKey(),
ad: AdMobService.createBannerAd()..load(),
),
);
}

最新更新