[英]Hero widget inits child widget multiple times
Whenever, I have a Hero
widget about a StatefulWidget
, the State.initState
method is called three times instead of once when navigating to that page. 无论何时,我有一个Hero
大约一个widget StatefulWidget
的State.initState
导航到该页面时方法被调用三次 ,而不是一次。
This obviously only happens when the other page also has a Hero
with the same tag. 显然,只有在其他页面也有带有相同标签的Hero
时,才会发生这种情况。
class Page extends StatelessWidget {
const Page({Key key}) : super(key: key);
@override
Widget build(BuildContext context) => Scaffold(body: Hero(tag: 'tag', child: HeroContent()));
}
class HeroContent extends StatefulWidget {
HeroContent({Key key}) : super(key: key);
@override
createState() => _HeroContentState();
}
class _HeroContentState extends State<HeroContent> {
@override
void initState() {
print('_HeroContentState.initState'); // printed three times with `Hero` widget and once without
super.initState();
}
@override
Widget build(BuildContext context) => Container();
}
Whenever I navigate to Page
, _HeroContentState.initState
is printed three times (and twice when popping a route). 每当我导航到Page
, _HeroContentState.initState
都会打印3次(弹出路径时两次)。
Fully reproducible example of this as a gist on GitHub . 作为GitHub上要点的完全可复制示例。
If I change the build method of Page
, to look like this (removing the Hero
widget): 如果我将Page
方法更改为如下所示(删除Hero
小部件):
@override
Widget build(BuildContext context) => Scaffold(body: HeroContent());
Now, _HeroContentState.initState
is only called once as it should be. 现在, _HeroContentState.initState
仅应被调用一次 。
How do I avoid Hero
inserting my widget three times? 如何避免Hero
插入小部件3次? How can I ensure that initState
is only called once or have a different method that is only called once? 如何确保initState
仅被调用一次或具有仅被调用一次的不同方法?
There is nothing you can do about that. 您对此无能为力。
The way Hero
works is that it moves in different locations in the widget tree in 3 steps: Hero
工作方式是分3个步骤在小部件树中的不同位置移动:
Usually, for such issue, you'd use a GlobalKey
, but that is not compatible with Hero
. 通常,对于此类问题,您将使用GlobalKey
,但这与Hero
不兼容。
As such, it is probably better to refactor your code such that initState
doesn't matter. 因此,最好重构代码,使initState
无关紧要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.