Как добавить рекламный баннер Admob в listView после каждых x строк

Я пытался добавлять рекламные баннеры Admob после каждых x строк представления SliverGrid, но не знаю, как это сделать.

Это мой виджет баннера Admob:

  const PsAdMobBannerWidget(),

Это мой полный класс, в котором я создаю бесконечное прокручиваемое представление SliverGrid:

 class _ProductListWithFilterViewState extends State<ProductListWithFilterView>
 with TickerProviderStateMixin {
final ScrollController _scrollController = ScrollController();

SearchProductProvider _searchProductProvider;
bool isVisible = true;
 @override
  void dispose() {
   super.dispose();
 }

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

_offset = 0;
_scrollController.addListener(() {
  if (_scrollController.position.pixels ==
      _scrollController.position.maxScrollExtent) {
    final String loginUserId =
    Utils.checkUserLoginId(valueHolder);
    _searchProductProvider.nextProductListByKey(
        loginUserId,
        _searchProductProvider.productParameterHolder);
  }
  setState(() {
    final double offset = _scrollController.offset;
    _delta += offset - _oldOffset;
    if (_delta > _containerMaxHeight)
      _delta = _containerMaxHeight;
    else if (_delta < 0) {
      _delta = 0;
    }
    _oldOffset = offset;
    _offset = -_delta;
  });

  print(' Offset $_offset');
});
}

final double _containerMaxHeight = 60;
double _offset, _delta = 0, _oldOffset = 0;
ProductRepository repo1;
dynamic data;
PsValueHolder valueHolder;
bool isConnectedToInternet = false;
bool isSuccessfullyLoaded = true;

void checkConnection() {
Utils.checkInternetConnectivity().then((bool onValue) {
  isConnectedToInternet = onValue;
  if (isConnectedToInternet && PsConfig.showAdMob) {
    setState(() {});
  }
});
}

@override
Widget build(BuildContext context) {
  if (!isConnectedToInternet && PsConfig.showAdMob) {
    print('loading ads....');
  checkConnection();
}
repo1 = Provider.of<ProductRepository>(context);
// data = EasyLocalizationProvider.of(context).data;
valueHolder = Provider.of<PsValueHolder>(context);

print(
    '............................Build UI Again ............................');
return
  // EasyLocalizationProvider(
  //     data: data,
  //     child:
  ChangeNotifierProvider<SearchProductProvider>(
      lazy: false,
      create: (BuildContext context) {
        final SearchProductProvider provider = SearchProductProvider(
            repo: repo1, psValueHolder: valueHolder);
        widget.productParameterHolder.itemLocationId =
            provider.psValueHolder.locationId;
        final String loginUserId =
        Utils.checkUserLoginId(valueHolder);
        provider.loadProductListByKey(loginUserId, widget.productParameterHolder );
        _searchProductProvider = provider;
        _searchProductProvider.productParameterHolder =
            widget.productParameterHolder;

        return _searchProductProvider;
      },
      child: Consumer<SearchProductProvider>(builder:
          (BuildContext context, SearchProductProvider provider,
          Widget child) {
        // print(provider.productList.data.isEmpty);
        // if (provider.productList.data.isNotEmpty) {
        return Column(
          children: <Widget>[
            const PsAdMobBannerWidget(),
            Expanded(
              child: Container(
                color: PsColors.coreBackgroundColor,
                child: Stack(children: <Widget>[
                  if (provider.productList.data.isNotEmpty &&
                      provider.productList.data != null)
                    Container(
                        color: PsColors.coreBackgroundColor,
                        margin: const EdgeInsets.only(
                            left: PsDimens.space4,
                            right: PsDimens.space4,
                            top: PsDimens.space4,
                            bottom: PsDimens.space4),
                        child: RefreshIndicator(
                          child: CustomScrollView(
                              controller: _scrollController,
                              physics:
                              const AlwaysScrollableScrollPhysics(),
                              scrollDirection: Axis.vertical,
                              shrinkWrap: true,
                              slivers: <Widget>[
                                SliverGrid(
                                  gridDelegate:
                                  const SliverGridDelegateWithMaxCrossAxisExtent(
                                      maxCrossAxisExtent: 280,
                                      childAspectRatio: 0.55),
                                  delegate: SliverChildBuilderDelegate(
                                        (BuildContext context, int index) {
                                      if (provider.productList.data !=
                                          null ||
                                          provider.productList.data
                                              .isNotEmpty) {
                                        final int count = provider
                                            .productList.data.length;
                                        return ProductVeticalListItem(
                                          coreTagKey: provider.hashCode
                                              .toString() +
                                              provider.productList
                                                  .data[index].id,
                                          animationController:
                                          widget.animationController,
                                          animation: Tween<double>(
                                              begin: 0.0, end: 1.0)
                                              .animate(
                                            CurvedAnimation(
                                              parent: widget
                                                  .animationController,
                                              curve: Interval(
                                                  (1 / count) * index,
                                                  1.0,
                                                  curve: Curves
                                                      .fastOutSlowIn),
                                            ),
                                          ),
                                          product: provider
                                              .productList.data[index],
                                          onTap: () {
                                            final Product product =
                                            provider.productList.data
                                                .reversed
                                                .toList()[index];
                                            final ProductDetailIntentHolder
                                            holder =
                                            ProductDetailIntentHolder(
                                                productId: provider
                                                    .productList
                                                    .data[index].id,
                                                heroTagImage: provider
                                                    .hashCode
                                                    .toString() +
                                                    product.id +
                                                    PsConst
                                                        .HERO_TAG__IMAGE,
                                                heroTagTitle: provider
                                                    .hashCode
                                                    .toString() +
                                                    product.id +
                                                    PsConst
                                                        .HERO_TAG__TITLE);
                                            Navigator.pushNamed(context,
                                                RoutePaths.productDetail,
                                                arguments: holder);
                                          },
                                        );
                                      } else {
                                        return null;
                                      }
                                    },
                                    childCount:
                                    provider.productList.data.length,
                                  ),
                                ),
                              ]),
                          onRefresh: () {
                            final String loginUserId =
                            Utils.checkUserLoginId(valueHolder);
                            return provider.resetLatestProductList(
                                loginUserId,
                                _searchProductProvider
                                    .productParameterHolder);
                          },
                        ))
                  else if (provider.productList.status !=
                      PsStatus.PROGRESS_LOADING &&
                      provider.productList.status !=
                          PsStatus.BLOCK_LOADING &&
                      provider.productList.status != PsStatus.NOACTION)
                    Align(
                      child: Container(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            Image.asset(
                              'assets/images/baseline_empty_item_grey_24.png',
                              height: 100,
                              width: 150,
                              fit: BoxFit.contain,
                            ),
                            const SizedBox(
                              height: PsDimens.space32,
                            ),
                            Padding(
                              padding: const EdgeInsets.only(
                                  left: PsDimens.space20,
                                  right: PsDimens.space20),
                              child: Text(
                                Utils.getString(context,
                                    'procuct_list__no_result_data'),
                                textAlign: TextAlign.center,
                                style: Theme.of(context)
                                    .textTheme
                                    .headline6
                                    .copyWith(),
                              ),
                            ),
                            const SizedBox(
                              height: PsDimens.space20,
                            ),
                          ],
                        ),
                      ),
                    ),
                  Positioned(
                    bottom: _offset,
                    width: MediaQuery.of(context).size.width,
                    child: Container(
                      margin: const EdgeInsets.only(
                          left: PsDimens.space12,
                          top: PsDimens.space8,
                          right: PsDimens.space12,
                          bottom: PsDimens.space16),
                      child: Container(
                          width: double.infinity,
                          height: _containerMaxHeight,
                          child: BottomNavigationImageAndText(
                              changeAppBarTitle: widget.changeAppBarTitle,
                              searchProductProvider:
                              _searchProductProvider)),
                    ),
                  ),
                  PSProgressIndicator(provider.productList.status),
                ]),
              ),
            )
          ],
        );
      }));
}
}

0 ответов

Другие вопросы по тегам