How to animate widget to new position on page transition?

Viewed 496

So basically I have a search bar widget that is in the center of the screen and when I click on the search bar, a new page is pushed using the Navigator. However on the page that is pushed on, the search bar is located at the top of the screen.

My question is how can I animate the search bar from the center to the top of the page on Navigator.of(context).pushNamed(...);

The functionality I am trying to achieve is identical to that of the Google app. The search bar is in the center but when you click it, it animates to the top of the page.

I have taken a look at animated routes and AnimatedPositioned widget but they don't seem all too appropriate for this functionality. I'm not very familiar with animations in general so I really have no clue where to start.

Thank you!

1 Answers

You should try Hero widget. Hero animates widgets between two pages.

Here is example code from doc

class PhotoHero extends StatelessWidget {
  const PhotoHero({ Key key, this.photo, this.onTap, this.width }) : super(key: key);

  final String photo;
  final VoidCallback onTap;
  final double width;

  Widget build(BuildContext context) {
    return SizedBox(
      width: width,
      child: Hero(
        tag: photo,
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            onTap: onTap,
            child: Image.asset(
              photo,
              fit: BoxFit.contain,
            ),
          ),
        ),
      ),
    );
  }
}

Wrap both widget inside Hero and give same tag in bot pages.

Related