Flutter典型错误: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’.

首先得知道Hero是Flutter中的一种动画形式,两个带有同样hero标识的元素在页面切换时会有一个飞动的效果,该效果由flutter自动实现。该标识对应的属性名为heroTag,在同一个页面内,每个heroTag只能拥有一个独一无二的值(和html种的id一样),如果重复就会抛出标题所示的异常‘There are multiple heroes that share the same tag within a subtree.’。解决办法自然是修改重复的heroTag值即可。

例如,FloatingActionButton就是自带的Hero动画的按钮元素,阅读源码可以发现,它的参数定义:

const FloatingActionButton({
    Key key,
    this.child,
    this.tooltip,
    this.foregroundColor,
    this.backgroundColor,
    this.focusColor,
    this.hoverColor,
    this.splashColor,
    this.heroTag = const _DefaultHeroTag(),
    this.elevation,
    this.focusElevation,
    this.hoverElevation,
    this.highlightElevation,
    this.disabledElevation,
    @required this.onPressed,
    this.mini = false,
    this.shape,
    this.clipBehavior = Clip.none,
    this.focusNode,
    this.autofocus = false,
    this.materialTapTargetSize,
    this.isExtended = false,
  })

heroTag的值默认被初始化为,一个常量const _DefaultHeroTag(),该常量定义为:

class _DefaultHeroTag {
  const _DefaultHeroTag();
  @override
  String toString() => '<default FloatingActionButton tag>';
}

所以当我们在一个页面种使用两个FloatingActionButton却不覆写它们的heroTag属性,它们会默认使用同一个标识,以致于冲突报错。同时,_DefaultHeroTag的toString方法返回‘<default FloatingActionButton tag>’,这就是为什么报错信息描述中会有‘<default FloatingActionButton tag>’的原因。

所以我们只需要修改一个FloatingActionButton的heroTag,让它不再是默认值即可:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: navigatorBar(context,title: 'xxx'),
      floatingActionButton: FloatingActionButton(
        onPressed: null,
        tooltip: 'Increment',
        child: Icon(Icons.add),
        heroTag: 'other',
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值