🐱
each Hero must have a unique non-null tag〜というエラーについて
概要
以下のようなエラーが発生したので備忘録です。
The following assertion was thrown during a scheduler callback:
There are multiple heroes that share the same tag within a subtree.
Within each subtree for which heroes are to be animated (i.e. a PageRoute subtree), each Hero must have a unique non-null tag.
In this case, multiple heroes had the following tag: <default FloatingActionButton tag>
Here is the subtree for one of the offending heroes: Hero
tag: <default FloatingActionButton tag>
state: _HeroState#42d31
前提
複数のFloatingActionButtonを配置しようとして該当のエラーが発生しました。
解決方法
「同じtag値が複数のHeroウィジェットで使用されている」という内容のエラーです。
Heroウィジェットはアニメーションを実現する際にtag属性を使用して対応するウィジェットを識別するため、同一のtagを持つHeroウィジェットが複数存在するとエラーになります。
FloatingActionButtonはheroTagプロパティを持つため、heroTag: null,
にするかそれぞれ個別のStringを設定することでエラーが解消されます。
そもそもHeroって何?
Heroウィジェットとは、2つの画面間でウィジェットをアニメーション付きで移動させるためのウィジェットです。使用することで、画面遷移時に「同じ要素が2つの画面間で移動している」ようになります。
遷移前と後で同じ値をタグに持たせることで実現できます。
Flutter Widget of the Week #17 Hero
実装するにはHeroウィジェットでWrapするか、heroTag propertyを持つウィジェットを使用することで実現できます。
FloatingActionButtonでheroTagを試してみた
ということで遷移前後のFloatingActionButtonのheroTagに同じ値を設定してみました。
Discussion