Flutter(三十七)Hero动画
2019-07-20 本文已影响0人
天色将变
特点
页面A有个圆形头像,页面B也有个圆形头像,头像图片是同一个。从A跳转到B时,一般都是硬性跳转,两个头像之间没有任何关系。而Hero的作用是:在跳转过程中,实现从A的头像过渡到B的头像的效果。
关键点
- 两个页面的头像都需要用Hero包裹住。
- 两个Hero的tag要一致。
如:
两个 页面:
image.png
image.png
PageA:
import 'package:flutter/material.dart';
import 'HeroAnimationRouteB.dart';
class HeroAnimationRouteTest extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'RaisedButton',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'RaisedButton'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("PageA"),
),
body: Container(
alignment: Alignment.topCenter,
child: Hero(
tag: "avatar",
child: Image.asset(
"images/avatar3.jpg",
width: 150,
)),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.arrow_right),
onPressed: () {
Navigator.push(context, PageRouteBuilder(pageBuilder:
(BuildContext context, Animation animation,
Animation secondaryAnimation) {
return HeroAnimationRouteB();
}));
},
),
);
}
}
PageB
import 'package:flutter/material.dart';
class HeroAnimationRouteB extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'PageB',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'RaisedButton'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Center(
child: Hero(
tag: "avatar", //唯一标记,前后两个路由页Hero的tag必须相同
child: Image.asset("images/avatar3.jpg",width: 300,),
),
);
}
}