hesham shawky
hesham shawky

Reputation: 1151

Flutter adding an item each x time on sliver list

I need to show an ad after each the 6th post of my sliver list, now I'm doing the below approach and it's working but it's replacing a post within an ad not actually adding it.

SliverList(
   delegate: SliverChildBuilderDelegate((context, i) {
      if ( i != 0 && i % 6 == 0 ) { // this replacing each 6th on the list not adding new
         // return ad widget
      }
      // return list item
   },
   childCount: dynamicListLength
)

Upvotes: 0

Views: 530

Answers (1)

enzo
enzo

Reputation: 11506

Here's how you can do with ListView.builder (it's easy to adapt it to SliverList):

import 'package:flutter/material.dart';

// Represents the default item
class ItemWidget extends StatelessWidget {
  final String text;
  
  const ItemWidget(this.text);
  
  @override
  Widget build(BuildContext context) {
    return Container(color: Colors.green, child: Text(text));    
  }
}

// Represents the ad widget
class AdWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(color: Colors.red, child: Text("Ad"));    
  }
}

class Screen extends StatelessWidget {
  final List<Widget> children;
  
  const Screen({this.children});
  
  @override
  Widget build(BuildContext context) {
    const int every = 6;
    
    final int size = children.length + children.length ~/ every;
    final List<Widget> items = List.generate(size, (i) {
      if (i != 0 && i % every == 0) return AdWidget();
      return children[i - i ~/ every];
    });
    
    return ListView.builder(
      itemBuilder: (_, i) => items[i],
      itemCount: items.length,
    );  
  }
}

Then you can use it like that:

Screen(children: [for (int i = 0; i < 30; i++) ItemWidget("$i")]);

Upvotes: 1

Related Questions