'Show ads after every 5 items on grid view in flutter
I want to show an ad after every 5 items in flutter grid view, so I want to make something like this,

keep in mind that the products and the ads will be in separate lists that are dynamically populated from json Also When the user click the Ad i want it to have Different Action, not the same as that of the product
my grid view code look something like this:
List<Product> _products = []; ///product list populated from json
List<Ads> _ads = []; ///ads i want to show populated from json
StaggeredGridView.countBuilder(
physics: NeverScrollableScrollPhysics(),
crossAxisCount: 4,
shrinkWrap:true,
itemCount: _products == null ? 0 : _products.length,
itemBuilder: (BuildContext context, int index) =>
Container(),
staggeredTileBuilder: (int index) =>
new StaggeredTile.fit(2),
mainAxisSpacing: 2.0,
crossAxisSpacing: 2.0,
);
Thanks alot,
Edit: what if I want to show the ads in my _ads list one by one according to their index in the builder, how will that turn out example of what I am trying to do:
GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
),
itemCount: 30,
itemBuilder: (BuildContext context, int index) {
return Card(
color: Colors.amber,
child: Center(
child: ((index + 1) % 6 == 0) ? Text( _ads[index].title) : Container(child: CachedNetworkImage(
memCacheHeight: 500,
imageUrl: CallApi().assetUrl() +
_products[index].image),),
),
);
},
),
Solution 1:[1]
Try below code
GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
),
itemCount: 30,
itemBuilder: (BuildContext context, int index) {
return Card(
color: Colors.amber,
child: Center(
child: ((index + 1) % 6 == 0) ? Text('AD') : Container( ),
),
);
},
),
Solution 2:[2]
Make the length of the grid adv + products length and then add this logic : It will show adv at every 5th position eg 5,10,15... etc
List<Product> _products = []; ///product list populated from json
List<Ads> _ads = []; ///ads i want to show populated from json
StaggeredGridView.countBuilder(
physics: NeverScrollableScrollPhysics(),
crossAxisCount: 4,
shrinkWrap:true,
itemCount: _products == null ? 0 : _products.length + _ads.length,
itemBuilder: (BuildContext context, int index) =>
if( (index + 1) % 6 == 0 ) showAdv()
else Container(),
staggeredTileBuilder: (int index) =>
new StaggeredTile.fit(2),
mainAxisSpacing: 2.0,
crossAxisSpacing: 2.0,
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ravindra S. Patil |
| Solution 2 | Sahil Hariyani |
