Skip to content

Instantly share code, notes, and snippets.

@TahaTesser
Created January 5, 2025 19:11
Show Gist options
  • Save TahaTesser/aed02d7d9b71456af3d81c160690df2c to your computer and use it in GitHub Desktop.
Save TahaTesser/aed02d7d9b71456af3d81c160690df2c to your computer and use it in GitHub Desktop.
Flipping Card Sample in Flutter
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(
home: FlipperSample(),
));
}
class FlipperSample extends StatefulWidget {
const FlipperSample({Key? key}) : super(key: key);
@override
State<FlipperSample> createState() => _FlipperSampleState();
}
class _FlipperSampleState extends State<FlipperSample>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<double> _animation;
Timer? _timer;
bool _isFlipped = false;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 600),
);
_animation = CurvedAnimation(
parent: _controller,
curve: Curves.easeInOutBack,
);
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
_isFlipped = !_isFlipped;
if (_isFlipped) {
_controller.forward(from: 0.0);
} else {
_controller.reverse(from: 1.0);
}
});
}
@override
void dispose() {
_timer?.cancel();
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flipper Sample'),
),
body: Center(
child: AnimatedBuilder(
animation: _animation,
builder: (_, child) {
final angle = pi * _animation.value;
Widget cardFace;
if (angle <= pi / 2) {
cardFace = Image.network(
'https://i.imgur.com/g5q6h7V.png',
fit: BoxFit.cover,
);
} else {
cardFace = Transform(
alignment: Alignment.center,
transform: Matrix4.rotationX(pi),
child: Image.network(
'https://i.imgur.com/3bTXwhT.png',
fit: BoxFit.cover,
),
);
}
return Transform(
alignment: Alignment.center,
transform: Matrix4.identity()
..setEntry(3, 2, 0.001)
..rotateX(angle),
child: cardFace,
);
},
),
),
);
}
}
@vicajilau
Copy link

Thanks so much!! You have taken away my fear of animations. 😃 I want to take this opportunity to make a suggestion for improvement in your line 75:

cardFace = Transform.flip(
              flipY: true,
              child: Image.network(
                  'https://i.imgur.com/3bTXwhT.png',
                  fit: BoxFit.cover,
                ),
            );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment