Home > Net >  Show ads after every 5 items on grid view in flutter
Show ads after every 5 items on grid view in flutter

Time:04-19

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

[enter image description here][1] [1]: https://i.stack.imgur.com/D94ym.png

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,

CodePudding user response:

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

CodePudding user response:

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