Flutter

Flutter(三十七)Hero动画

2019-07-20  本文已影响0人  天色将变
特点

页面A有个圆形头像,页面B也有个圆形头像,头像图片是同一个。从A跳转到B时,一般都是硬性跳转,两个头像之间没有任何关系。而Hero的作用是:在跳转过程中,实现从A的头像过渡到B的头像的效果。

关键点

如:
两个 页面:


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,),
      ),
    );
  }
}
欢迎关注我的公众号:Flutter和Dart开发实践
让我们共同学习进步,It is never too late to learn!
image.png
上一篇下一篇

猜你喜欢

热点阅读