Flutter 动画篇——Hero

2020-05-01  本文已影响0人  _破晓之翼

Hero 动画使用方法

我们先来看一下效果rt:

image

Hero动画实现了元素共享功能,简单来说:

Hero动画就是在路由切换时,有一个共享的Widget可以在新旧路由间切换,由于共享的Widget在新旧路由页面上的位置、外观可能有所差异,所以在路由切换时会逐渐过渡,这样就会产生一个Hero动画。

要触发Hero动画,Hero必须存在于新页面动画的第一帧。

并且一个路由里只能有一个Hero 的 tag(什么是tag ?顾名思义,tag就是Hero控件的一个标签,用来判定唯一性,前后两个路由页Hero的tag必须相同)。


然后就是使用方法了:

“来人!上代码!”

//第一个页面里定义了一张图片,即为我们要进行元素共享的Widget
Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: GestureDetector(
        onTap: (){
          Navigator.push(
            context,
            new MaterialPageRoute(builder: (context) => new SecondPage()),
          );
        },
        child: Center(
            child: Hero(
              tag: "xx",
              child: Container(
                height: 200,
                width: 300,
                child: Image.asset("images/bc_load.jpg"),
              )
            )
        ),
      )
    );
  }

接下来是第二个页面:

class SecondPage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
      return Scaffold(
        appBar: AppBar(
          title: Text("新的一页"),
        ),
        body: GestureDetector(
          onTap: (){
            Navigator.pop(context);
          },
          child: Column(
            children: <Widget>[
              Hero(
                  tag: "xx",
                  child: Image.asset("images/bc_load.jpg"),
              ),
              Text("这是新的一页",
                  style: TextStyle(decoration:TextDecoration.none,
                  fontSize: 40)),
            ],
          )
        )
      );
  }
}

可以看到只需要在你想要共享的widget 前加上 Hero,写上 tag即可。

大功告成!!!!!

上一篇下一篇

猜你喜欢

热点阅读