问题描述
我正在使用以下代码,通过使用带有Firestore作为数据库的分页来检索Flutter应用程序中的列表,效果很好。我指的是原生广告的Flutter_native_admob
依赖性。但是我不知道如何在listview.builder
中实现它,同时需要实现分页。
就像在instagram中一样,在特定数量的帖子之后,原生广告就会显示出来,我需要以类似的方式展示添加内容。那怎么可能?
_getProducts() async {
query = Firestore.instance.collection("users").document(uid).collection('my_favorites').orderBy("timestamp",descending: true).limit(5);
setState(() {
_loadingnotifications = true ;
});
QuerySnapshot _querySnapshot = await query.getDocuments();
_lastDocument = _querySnapshot.documents[_querySnapshot.documents.length - 1];
_notifications = _querySnapshot.documents;
setState(() {
_loadingnotifications = false;
});
}
_getMoreNotifications() async {
print("new docs loaded");
if(_moreProductsAvailable == false ){
return;
}
if(_loadingMore == true ){
return;
}
_loadingMore = true;
query = Firestore.instance.collection("users").document(uid).collection('my_favorites').orderBy("timestamp",descending: true).startAfter([_lastDocument.data['timestamp']]).limit(5);
QuerySnapshot _querySnapshot = await query.getDocuments();
if (_querySnapshot.documents.length <5){
_moreProductsAvailable = false;
}
_lastDocument = _querySnapshot.documents[_querySnapshot.documents.length - 1];
_notifications.addAll(_querySnapshot.documents);
setState(() {
_loadingnotifications = false;
});
_loadingMore = false;
}
LISTVIEW.BUILDER
Flexible(
child:_loadingnotifications == true ? Container(child: Center(child: Text("Loading..."),),) :Container(child: _notifications.length == 0? Center(
child: Text("No Marked Posts Yet!"),) :
new ListView.builder(
controller: _scrollController,itemCount: _notifications.length,itemBuilder: (BuildContext ctx,int index){
String itemTitle = _notifications[index].data['itemTitle'];
return ItemCard(itemTitle: itemTitle,);
}),)
),
我知道如何创建admob帐户并在应用程序中初始化Flutter_native_admob
,但不知道如何像instagram和分页一样将其放入列表中。
解决方法
您可以在循环中添加一个计数器变量,然后在最终列表中添加小部件之前,可以检查一下,只要计数器变量是5的倍数,则添加广告小部件,否则添加普通小部件,这会将广告添加到您的列表中每5个普通小部件之后。
您可以检查以下内容以供参考: https://medium.com/@vitopiegari/embedding-ads-into-flutters-widget-tree-with-admob-flutter-ae59c3a66492
,使用 ListView.builder
代替 ListView.separated
。
然后,在 separatorBuilder 属性中,您可以添加广告。
例如:
ListView.separated(
physics: BouncingScrollPhysics(),shrinkWrap: true,itemBuilder: (context,i) {
return ListTile();
},separatorBuilder: (context,index) {
if (index % 10 == 9 && index != 0) return BannerAd();
return const SizedBox();
},itemCount: _listLength,),