Flutter :- 这个 AdWidget 已经在 Widget 树中了如何禁用此异常这是什么意思?

问题描述

所以我在列表中插入了 admob 广告。我在列表视图中添加了无限滚动的功能。因此,当用户滚动到列表末尾时,新项目会添加到列表中。对于这些项目,我还在其中添加了 admob 广告。

因此,当用户滚动到末尾时,新项目和广告会添加到列表中。那时捕获了以下异常。那么如何解决这个异常。

======== Exception caught by widgets library =======================================================
The following assertion was thrown building AdWidget-[#53ef3](dirty,state: _AdWidgetState#850ac):
This AdWidget is already in the Widget tree


If you placed this AdWidget in a list,make sure you create a new instance in the builder function with a unique ad object.
Make sure you are not using the same ad object in more than one AdWidget.

The relevant error-causing widget was: 
  AdWidget-[#53ef3] file:///D:/flutter%20project/memer/lib/pages/TimeLinePage.dart:198:42
When the exception was thrown,this was the stack: 
#0      _AdWidgetState.build (package:google_mobile_ads/src/ad_containers.dart:371:7)
#1      StatefulElement.build (package:flutter/src/widgets/framework.dart:4612:27)
#2      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4495:15)
#3      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4667:11)
#4      Element.rebuild (package:flutter/src/widgets/framework.dart:4189:5)

代码:-

return ListView.builder(itemBuilder: (context,index){
        //print(posts);
        if(posts[index] is Post){
          return posts[index];
        }
        else{
          final Container adContainer = Container(
                                  alignment: Alignment.center,child: AdWidget(key: UniqueKey(),ad: posts[index] as BannerAd),//AdmobService.createBannerAd()..load()
                                  height: 50,);
                      return adContainer;
        }
      },itemCount: posts.length,controller: scrollController,physics: const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()));
    }

解决方法

当你想添加一个新的横幅时,你必须为它分配一个新的 ID

BannerAd(adUnitId: 'somethingDifferentThanTheOneInTheTree)

正如错误日志中明确指出的:

如果您将此 AdWidget 放在列表中,请确保在 具有唯一广告对象的构建器函数。确保您没有使用 多个 AdWidget 中的相同广告对象。

,

除了 Kafil Khan 的 answer,您还可以使用 StatefulBuilder 包装容器小部件。

示例:

Widget bannerAdWidget() {
    return StatefulBuilder(
      builder: (context,setState) => Container(
        child: AdWidget(ad: _bannerAd),width: _bannerAd.size.width.toDouble(),height: 100.0,alignment: Alignment.center,),);
  }
,

问题在于您一次又一次地放置相同的小部件。您可以通过创建一个新的 StatefulWidget 类并返回 Adwidget 来解决此问题,这将多次构建相同的小部件,它的工作方式类似于构建器。这解决了我的问题,希望它也适用于您! :)

您也不必为单个广告单元提供多个 ID。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...