使用admob的Flutter Listview

r8uurelv  于 2023-06-24  发布在  Flutter
关注(0)|答案(1)|浏览(133)

当我想把广告之间的列表视图我想每2卡添加广告,但只是前两张卡显示和广告,而其他列表不显示

ListView.builder(
    itemCount: foundUser.length,
    itemBuilder: (BuildContext context, index) {
        if (index % 2 == 0 && index > 0) {
             return const CustomBannerAd();
        }
        return CustomCard();
    }

我想帮助你请把广告之间的列表视图

yv5phkfx

yv5phkfx1#

你可以计算广告指数和项目指数来实现你想要的。下面是一个简化的例子,其中有两个项目之间的广告。

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        useMaterial3: true,
      ),
      home: const MyHomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Theme.of(context).colorScheme.inversePrimary,
          title: const Text('Demo'),
        ),
        //actual code starts here
        body: const _ListWithAds());
  }
}

class _ListWithAds extends StatelessWidget {
  const _ListWithAds();

  List<int> get items => Iterable.generate(100, (i) => i).toList();

  @override
  Widget build(BuildContext context) {
    var length = (items.length * 1.5).floor();

    // if you don't want last item to be an Ad, uncomment below line
    // if (length % 3 == 0) {
    //   length--;
    // }

    return ListView.builder(
        itemCount: length,
        itemBuilder: (BuildContext context, index) {
          if (index % 3 == 2) {
            return const ListTile(
              title: Text('Ad'),
            );
          } else {
            final newIndex = (index * 2 / 3).ceil();
            return ListTile(
              title: Text('Item #$newIndex'),
            );
          }
        });
  }
}

输出:

相关问题