Flutter - 如何在 listview.separated 中的每第 n 行(每第 4 行)插入广告

Flutter - How to insert the ad in every nth row (every 4th row) in listview.separated

我正在使用 Listview.separated 并且我正在使用 google_mobile_ads as the package to integrate the ads. I followed the example here 但是我无法得到我所需要的。 我在 separatorBuilder 中调用了横幅广告,但在每第 n 行之后给出分隔线或广告。

我需要在 listview.separated 的每 4 行之后插入。

ListView.separated(
          scrollDirection: Axis.vertical,
          shrinkWrap: true,
          controller: _scrollController,
          itemCount: articleslist.length + 1,
          itemBuilder: (BuildContext context, int index) {
            if (index == articleslist.length) {
              _loading = true;
              return Center(
                child: Row(
                  children: [
                    Container(
                      padding: EdgeInsets.all(5),
                      child: CircularProgressIndicator(
                        color: Colors.deepOrange[800],
                      ),
                    ),
                    SizedBox(
                      width: 15,
                    ),
                    Text(
                      'Articles are being loaded...',
                      style: TextStyle(color: Colors.deepOrange[800]),
                    )
                  ],
                ),
              );
            } else {
              Text(
                'No data to load',
                style: TextStyle(color: Colors.deepOrange[800]),
              );
            }
            if (articleslist.length == 0) {
              return Container(
                  child: Center(
                      child: Text('Loading...',
                          style: TextStyle(color: Colors.deepOrange))));
            } else {
              var imgUrl = articleslist[index].img.toString();
              imgUrl = BaseUrl + imgUrl.toString();
              var title = articleslist[index].title;
              title = title.replaceAll(RegExp(r'<[^>]*>'), '');
              var body = articleslist[index].body;
              body = body.replaceAll(RegExp(r'<[^>]*>'), '');
              

              return InkWell(
                onTap: () {
                  print('Tapped : ${articleslist[index].nid}');
                  print(index);
                  Navigator.push(
                      context,
                      new MaterialPageRoute(
                          builder: (context) => DetailPage(
                            articleslist[index].title,
                            articleslist[index].img,
                            articleslist[index].nid,
                            articleslist[index].uid,
                            articleslist[index].created,
                          )));
                },
                child: Container(
                  padding: EdgeInsets.fromLTRB(8.0, 6.0, 8.0, 0.0),
                  child: Row(
                    // crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: <Widget>[
                      Container(
                        width: 120,
                        height: 75,
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(8),
                          child: imgUrl == 'No img'
                              ? Image.asset('images/placeholder.png',
                              height: 220, fit: BoxFit.cover)
                              : FadeInImage.assetNetwork(
                            placeholder: 'images/placeholder.png',
                            image: imgUrl,
                            height: 220,
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                      const SizedBox(
                        width: 20,
                      ),
                      Expanded(
                        child: Column(
                          mainAxisAlignment:
                          MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                              title,
                              style: TextStyle(
                                  color: Colors.black, fontSize: 16),
                            ),
                            const SizedBox(
                              height: 10,
                            ),
                            Text(
                              'author : $uid',
                              style: TextStyle(
                                fontSize: 10,
                              ),
                            ),
                            const SizedBox(
                              height: 5,
                            ),
                            Text(
                              created,
                              style: TextStyle(
                                fontSize: 10,
                              ),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              );
            }
          },
          separatorBuilder: (context, index) => Divider(),
        ),

您可以使用 ListView.separated 和“%”运算符将项目添加到第 n 个位置。

您只需将“%”运算符后的数字“4”更改为要添加到第 n 位的内容。

...
if ((index + 1) % 4 == 0) {
...

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  FocusNode focusNode = FocusNode();
  @override
  void initState() {
    super.initState();
    focusNode.addListener(() {
      print('1:  ${focusNode.hasFocus}');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    return ListView.separated(
      itemCount: 20,
      separatorBuilder: (context, index) {
        if ((index + 1) % 4 == 0) {
          return Container(
            height: 100,
            color: Colors.yellow,
            child: Text('it is ads'),
          );
        } else {
          return Container();
        }
      },
      itemBuilder: (context, index) {
        return Container(
          height: 100,
          color: Colors.blue,
          child: Text('item index: $index'),
        );
      },
    );
  }
}