Flutter--Hero component

 Sometimes if you want a certain component of this page, you can transition to the next page through animation, such as in Apple music, play the music icon at the bottom, and when you open the play page, you can zoom in to the position of the play page by yourself. At this time, you need to use The page jump animation and the hero component are implemented together.

Note: Hero components cannot be nested. For example, if a Container is marked as hero, its children cannot be Hero components.

import 'package:flutter/material.dart';

const String iconTag = "icon";
const String titleTag = "title";

class HeroAnimationPage extends StatelessWidget {
  const HeroAnimationPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(children: [
        const Spacer(),
        InkWell(
          child: Container(
            margin: const EdgeInsets.all(16),
            padding: const EdgeInsets.all(4),
            color: Colors.blueAccent,
            child: Row(children: [
              Container(
                width: 50,
                height: 50,
                color: Colors.grey,
              ).hero(iconTag),
              const Text("Title").hero(titleTag)
            ],),
          ),
          onTap: () {
            Navigator.push(context, PageRouteBuilder(pageBuilder: (BuildContext context, animation, secondaryAnimation,) {
                return FadeTransition(
                  opacity: animation,
                  child: const Scaffold(
                    body: HeroTargetPage(),
                  ),
                );
              },
            ));
          },
        )
      ],),
    );
  }
}


class HeroTargetPage extends StatelessWidget {
  const HeroTargetPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Column(children: [
          Container(color: Colors.red, width: 200, height: 200,).hero(iconTag),
          Row(children: [const Text("Title", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 22),).hero(titleTag)],  mainAxisAlignment: MainAxisAlignment.center,)
        ], mainAxisAlignment: MainAxisAlignment.spaceAround,),
        color: Colors.blueAccent,
      ),
    );
  }
}

extension WidgetExt on Widget {
  Hero hero(String tag) {
    return Hero(tag: tag, child: this);
  }
}

Guess you like

Origin blog.csdn.net/weixin_41735943/article/details/123147315