微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。