Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Adding advertise every nth row in ListView.builder

In Android Studio, I was using RecyclerView.Adapter and RecyclerView.ViewHolder with getItemViewType() to determine the position of a row in RecyclerView and put advertisement every 10th row. but in the flutter, I don't know how to achieve that and I was looking around the web for the last two days I could not find anything or maybe I don't know what it's called in the flutter. I may not need a code example, I need some guidance on how it's possible or what it's called to look around the web. Tip: I'm using ListView.builder to receive data from API and show it in ListView.builder.

EDIT: I'm adding my code to make it more clear:

void main() {
  runApp(MaterialApp(
    debugShowCheckedModeBanner: false,
    home: HomePage(),
  ));
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  Map data;
  List recentNews;
  var _textController = TextEditingController();

  Future getRecent() async {
    String url = 'https://example.com/api';
    http.Response response = await http.get(url, headers: {HttpHeaders.authorizationHeader: ApiKey});
    data = json.decode(response.body);
    setState(() {
      recentNews = data["data"];
    });
  }

  @override
  void initState() {
    super.initState();
    getRecent();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
        home: DefaultTabController(
        child: Scaffold(
      appBar: new AppBar(
        iconTheme: new IconThemeData(color: Colors.black),
        backgroundColor: Colors.white,
        title: Text("TEST", style: TextStyle(color: Colors.black),),
      ),
      body:
          ListView.builder(
            itemCount: recentNews == null ? 0 : recentNews.length,
            itemBuilder: (BuildContext context, int index) {
              String serverTime = "${recentNews[index]["createdAt"]["date"]}";
              DateTime time = DateTime.parse(serverTime);
              String agoTime = timeago.format(time);
              return Card(
                child: Padding(
                  padding: const EdgeInsets.all(10.0),
                  child: InkWell(
                    onTap: (){
                      var route = new MaterialPageRoute(
                        builder: (BuildContext context) =>
                        new WebView(slug: recentNews[index]["slug"], title: recentNews[index]["title"]),
                      );
                      Navigator.of(context).push(route);
                    },
                    child: Column(
                      children: <Widget>[
                        new Container(
                            child: new Image.network(recentNews[index]["image_url"])
                        ),
                        Padding(
                          padding: const EdgeInsets.all(10.0),
                          child: Text("${recentNews[index]["title"]}",
                            style: TextStyle(
                              fontSize: 20.0,
                              fontWeight: FontWeight.w700,
                            ),),
                        ),
                        new Row(
                          children: <Widget>[
                            Text("${recentNews[index]["source"]["name"]}"),
                            Text(" - "),
                            Text(agoTime),
                          ],
                        )
                      ],
                    ),
                  ),
                ),
              );
            },
          ),
    ),
        ),
    );
  }
}
like image 857
user2682025 Avatar asked Oct 17 '25 10:10

user2682025


2 Answers

Try ListView.separated()

In the separated() constructor, you generate a list and you can specify the separator between each item.

    ListView.separated( 
        itemBuilder: (context, position) { 
        return ListItem(); 
    }, 
    separatorBuilder: (context, position) { 
        return Container(child: (index != 0 && index % 5 == 0) ? 
        AdmobBanner(adUnitId: getBannerAdUnitId(), adSize: 
        AdmobBannerSize.BANNER, listener: (AdmobAdEvent event, Map args) 
        { //handleEvent(event, args, 'Banner'); },
 ) : Divider( height: 2.0, )); 
        }, itemCount: itemCount, //nth item as ads. 
)

Good luck.

like image 159
Dynamo Army Avatar answered Oct 20 '25 00:10

Dynamo Army


Try ListView.separated()

In the separated() constructor, you generate a list and you can specify the separator between each item.

ListView.separated(
      itemBuilder: (context, position) {
        return ListItem();
      },
      separatorBuilder: (context, position) {
        return SeparatorItem();
      },
      itemCount: itemCount,  //nth item as ads. 
),

This type of list lets you dynamically define separators, have different types of separators for different types of items, add or remove separators when needed, etc.

This implementation can also be used for inserting other types of elements (advertisements for example) easily and without any modification to the main list in the middle of the list items.

like image 24
CharlesC Avatar answered Oct 20 '25 00:10

CharlesC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!