Flutter: There are multiple heroes that share the same tag within a subtree异常

2,563 阅读1分钟

今天写Demo的时候遇到了下面的错误:

I/flutter: ══╡ EXCEPTION CAUGHT BY SCHEDULER LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter: The following assertion was thrown during a scheduler callback:
I/flutter: There are multiple heroes that share the same tag within a subtree.
I/flutter: Within each subtree for which heroes are to be animated (i.e. a PageRoute subtree), each Hero must
I/flutter: have a unique non-null tag.
I/flutter: In this case, multiple heroes had the following tag: <default FloatingActionButton tag>
I/flutter: Here is the subtree for one of the offending heroes:
I/flutter: # Hero(tag: <default FloatingActionButton tag>, state: _HeroState#c0b28)
...

大致意思是说:

在程序回调的的时候发生了以下断言:

在子树中有多个Hero 对象共用了一个tag,每个Hero对象的tag必须是惟一的。

并且指出了是FloatingActionButton中的tag 有冲突。

以前都没注意到这个东西,来看一下FloatingActionButton 中的 tag吧。

在这里插入图片描述
在这里插入图片描述
可以看到 heroTag 有个默认值:<default FloatingActionButton tag>

而刚好我的页面中有两个 FloatingActionButton,所以就导致heroTag 冲突了。

解决办法很简单,给FloatingActionButton 的heroTag 赋一个新的值。

在这里插入图片描述
这样就可以正常使用了。

归根到底还是 Hero对象中的tag必须唯一,从下面报错的地方就可以看到了:

在这里插入图片描述
所以类似报错都可以直接找到有使用Hero对象的地方就行了。