首页 > 解决方案 > Flutter 在子树中共享相同标签的多个英雄

问题描述

我正在尝试从帖子视图屏幕到全屏帖子视图的英雄动画。据我所见,这似乎很正常(我的代码),我真的不明白为什么我会收到这个错误......

我的代码中没有任何其他 Hero 小部件,所以我不明白为什么会出现此错误...

这是我得到的错误:

There are multiple heroes that share the same tag within a subtree.

这是我的代码:

Stack(
            alignment: Alignment.center,
            children: <Widget>[
              Hero(
                tag: 'test',
                child: Container(
                  height: MediaQuery.of(context).size.width,
                  child: Padding(
                    padding: const EdgeInsets.all(6.0),
                    child: Align(
                      alignment: Alignment.topRight,
                      child: Container(
                        decoration: BoxDecoration(
                          color: Colors.grey.shade400.withOpacity(0.5),
                          borderRadius: BorderRadius.circular(12.0),
                        ),
                        width: 120,
                        height: 40,
                        child: ListView.builder(
                          scrollDirection: Axis.horizontal,
                          itemCount: 3,
                          itemBuilder: (BuildContext context, int index) {
                            return _configureEmoji(index);
                          },
                        ),
                      ),
                    ),
                  ),
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: CachedNetworkImageProvider(widget.post.imageURL),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
              ),
            ],
          ),

这是我希望英雄动画去的地方:

class FullScreenView extends StatelessWidget {
  final String imageURL;
  FullScreenView({this.imageURL});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Hero(
        tag: 'test',
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: CachedNetworkImageProvider(imageURL),
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
    );
  }
}

非常感谢,我非常感谢您的帮助!

标签: androidiosflutteranimationdart

解决方案


合理的理由

Hero 小部件不知道您单击了哪个英雄,因此它使用下一个屏幕的 Hero 标签作为参考来执行屏幕搜索,该屏幕搜索将通过查找具有相同标签的 Hero 来关闭。如果有多个英雄具有相同的标签,则会返回错误,因为不知道应该由哪个英雄来制作动画。

在此处输入图像描述

解决方案

我使用的解决方案是使用其中的内容作为参考来识别每个英雄,并在导航中将这个 id(标签)插入到导航推送参数中,然后将此 id 添加到目标屏幕的英雄中。

对您的项目来说,最合理的方法是使用帖子 ID 作为英雄标签,当将帖子数据发送到下一个屏幕时,已经使用屏幕英雄上的帖子 ID。

在此处输入图像描述


推荐阅读