1. Hero 组件简介
Hero
组件的核心功能是实现页面跳转时的共享元素动画(Shared Element Transition)。它通过在两个页面中定义相同的 tag
值,自动检测并创建平滑的过渡动画。
2. Hero 组件的基本使用
基本示例
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: FirstPage(),
));
}
class FirstPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('First Page')),
body: Center(
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondPage()),
);
},
child: Hero(
tag: 'hero-image',
child: Image.network(
'https://i-blog.csdnimg.cn/direct/c490220d315a4f1681caf7da88352829.png',
width: 250,
),
),
),
),
);
}
}
class SecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Second Page')),
body: Center(
child: Hero(
tag: 'hero-image',
child: Image.network(
'https://i-blog.csdnimg.cn/direct/c490220d315a4f1681caf7da88352829.png',
width: 500,
),
),
),
);
}
}
在上述示例中,两个页面分别包含相同 tag
的 Hero
组件。当用户点击图片进入 SecondPage
时,Flutter 会自动创建动画,使图片从 FirstPage
平滑过渡到 SecondPage
。
3. Hero 组件的关键属性
- tag
- 必填属性,标识
Hero
组件,使 Flutter 知道如何进行匹配。
- child
- 需要动画过渡的子组件。
- flightShuttleBuilder
- 用于自定义动画过程中的
Hero
组件外观。
4. 自定义动画效果 (flightShuttleBuilder
)
通过 flightShuttleBuilder
,可以控制动画过程中的 Hero
外观。例如:
Hero(
tag: 'hero-image',
flightShuttleBuilder: (flightContext, animation, direction, fromContext, toContext) {
return RotationTransition(
turns: animation,
child: toContext.widget,
);
},
child: Image.network('https://i-blog.csdnimg.cn/direct/c490220d315a4f1681caf7da88352829.png', width: 100,),
)
这样在页面切换时,图片会旋转而不是默认的缩放过渡。
5. Hero 组件的优化建议
- 尽量减少
Hero
组件的嵌套,避免动画卡顿。 - 确保
tag
唯一,否则可能导致动画异常。 - 避免使用复杂布局作为
Hero
组件,提升性能。
6. 结论
Hero
组件是 Flutter 提供的一个简单但强大的动画工具,能够显著提升应用的视觉效果。通过合理利用 tag
、flightShuttleBuilder
等属性,可以实现丰富的过渡动画,让页面切换更加生动自然。