How do I make this transition animation? Whenever the user clicks on the icon it should expand and go the center and after 2 seconds it should disappear.
I tried using AnimatorContainer but whenever I expand the icon size, it is pushing all the other widget out of bounds.
You can use Hero widget to fly the the widget across pages.
Here's an example:
Let's assuming you want to move CircleAvatar. Wrap it with the Hero widget like this:
InkWell(
onTap: gotoNextpage,
child: const Hero(
tag: 'the-flying-widget', // <- You can use any string, just make sure to keep it the same on both pages
child: CircleAvatar(
radius: 30,
child: Icon(Icons.add),
),
),
),
Optional: Use PageRouteBuilder
to show a fade animation while navigating to Page2
for a smoother experience or else you can simply use MaterialPageRoute
.
void gotoNextpage() {
Navigator.of(context).push(
PageRouteBuilder(
pageBuilder: (
context,
animation,
secondaryAnimation,
) {
return const Page2();
},
transitionsBuilder: (
context,
animation,
secondaryAnimation,
child,
) {
return FadeTransition(
opacity: animation,
child: child,
);
},
transitionDuration: const Duration(seconds: 1),
reverseTransitionDuration: const Duration(seconds: 1),
),
);
}
On the next page say Page2,
initState()
WillPopScope
or PopScope
(whichever is available as per your Flutter version) and return false to prevent popping the page manually class Page2 extends StatefulWidget {
const Page2({super.key});
@override
State<Page2> createState() => _Page2State();
}
class _Page2State extends State<Page2> {
@override
void initState() {
super.initState();
Future.delayed(const Duration(seconds: 2)).then((value) {
Navigator.pop(context);
});
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async => false,
child: const Scaffold(
body: Center(
child: Hero(
tag: 'the-flying-widget',
child: CircleAvatar(
radius: 50,
child: Icon(Icons.add),
),
),
),
),
);
}
}
Here's the result: