Skip to content

Instantly share code, notes, and snippets.

@Roaa94
Last active March 6, 2023 14:07
Show Gist options
  • Save Roaa94/ca51f87da5dca6645f53cd6ed2548fec to your computer and use it in GitHub Desktop.
Save Roaa94/ca51f87da5dca6645f53cd6ed2548fec to your computer and use it in GitHub Desktop.
Flutter Hero Animation with Card Flip Effect
import 'package:flutter/material.dart';
import 'dart:math';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Hero Card Flip Effect',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.cyan,
),
home: const FirstPage(),
);
}
}
class FirstPage extends StatelessWidget {
const FirstPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: GestureDetector(
onTap: () {
Navigator.of(context).push(
PageRouteBuilder(
transitionDuration: const Duration(milliseconds: 600),
reverseTransitionDuration: const Duration(milliseconds: 600),
pageBuilder: (
BuildContext context,
Animation<double> animation,
_,
) {
return const SecondPage();
},
transitionsBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
return FadeTransition(
opacity: animation,
child: child,
);
},
),
);
},
child: Hero(
tag: 'hero-animation',
flightShuttleBuilder:
(_, Animation<double> animation, __, ___, ____) {
final rotationAnimation = Tween<double>(
begin: 0.0,
end: 2.0,
).animate(animation);
return AnimatedBuilder(
animation: rotationAnimation,
child: const Card(),
builder: (context, child) {
return Transform(
transform: Matrix4.identity()
..setEntry(3, 2, 0.003)
..rotateX(rotationAnimation.value * pi),
alignment: Alignment.center,
child: child,
);
},
);
},
child: Transform(
transform: Matrix4.identity()
..setEntry(3, 2, 0.003)
..rotateX(0),
alignment: Alignment.center,
child: const Card(),
),
),
),
),
);
}
}
class SecondPage extends StatelessWidget {
const SecondPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
),
body: SafeArea(
child: Column(
children: [
const SizedBox(height: 20),
Center(
child: Hero(
tag: 'hero-animation',
child: Transform(
transform: Matrix4.identity()
..setEntry(3, 2, 0.003)
..rotateX(2 * pi),
alignment: Alignment.center,
child: const Card(),
),
),
),
],
),
),
);
}
}
class Card extends StatelessWidget {
const Card({super.key});
@override
Widget build(BuildContext context) {
return Container(
width: 180,
height: 180,
decoration: BoxDecoration(
color: Colors.cyan,
borderRadius: BorderRadius.circular(15),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment