Show ads after every 5 items on grid view in flutter

Viewed 221

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),),
      ),
    );
  },
),
2 Answers

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( ),
          ),
        );
      },
    ),

Result Screen-> imGe

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,
    );

Related