Complete example code of making flip card animation in Flutter

  • 2021-12-21 04:54:05
  • OfStack

Directory preface uses self-written code Preview
The complete code uses the third plug-in Coding conclusion

Preface

This article will show you two complete examples of making flip card animation in Flutter. The first example is implemented from scratch, and the second example uses the third-party package. Cut the gossip and let's get to work.

Use self-written code

This example uses the Transformation widget to create a flip card effect.

Preview

The demo application we are going to build shows two cards that hide some secrets. You can uncover what is behind the mask by pressing the "Reveal Secrets" button. The top card shows a horizontal flip animation, and the bottom card shows a vertical flip animation.

Complete code


// main.dart
import 'package:flutter/material.dart';
import 'dart:math';
​
void main() {
  runApp(MyApp());
}
​
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        // Remove the debug banner
        debugShowCheckedModeBanner: false,
        title: 'Kindacode.com',
        theme: ThemeData(
          primarySwatch: Colors.amber,
        ),
        home: HomePage());
  }
}
​
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
​
  @override
  _HomePageState createState() => _HomePageState();
}
​
class _HomePageState extends State with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation _animation;
  AnimationStatus _status = AnimationStatus.dismissed;
​
  @override
  void initState() {
    super.initState();
    _controller =
        AnimationController(vsync: this, duration: Duration(seconds: 1));
    _animation = Tween(end: 1.0, begin: 0.0).animate(_controller)
      ..addListener(() {
        setState(() {});
      })
      ..addStatusListener((status) {
        _status = status;
      });
  }
​
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(
              height: 30,
            ),
            // Horizontal Flipping
            Transform(
              alignment: FractionalOffset.center,
              transform: Matrix4.identity()
                ..setEntry(3, 2, 0.0015)
                ..rotateY(pi * _animation.value),
              child: Card(
                child: _animation.value <= 0.5
                    ? Container(
                        color: Colors.deepOrange,
                        width: 240,
                        height: 300,
                        child: Center(
                            child: Text(
                          '?',
                          style: TextStyle(fontSize: 100, color: Colors.white),
                        )))
                    : Container(
                        width: 240,
                        height: 300,
                        color: Colors.grey,
                        child: Image.network(
                          'https://www.kindacode.com/wp-content/uploads/2021/09/girl.jpeg',
                          fit: BoxFit.cover,
                        )),
              ),
            ),
            // Vertical Flipping
            SizedBox(
              height: 30,
            ),
            Transform(
              alignment: FractionalOffset.center,
              transform: Matrix4.identity()
                ..setEntry(3, 2, 0.0015)
                ..rotateX(pi * _animation.value),
              child: Card(
                child: _animation.value <= 0.5
                    ? Container(
                        color: Colors.deepPurple,
                        width: 240,
                        height: 300,
                        child: Center(
                            child: Text(
                          '?',
                          style: TextStyle(fontSize: 100, color: Colors.white),
                        )))
                    : Container(
                        width: 240,
                        height: 300,
                        color: Colors.grey,
                        child: RotatedBox(
                          quarterTurns: 2,
                          child: Image.network(
                            'https://www.kindacode.com/wp-content/uploads/2021/09/flower.jpeg',
                            fit: BoxFit.cover,
                          ),
                        )),
              ),
            ),
            ElevatedButton(
                onPressed: () {
                  if (_status == AnimationStatus.dismissed) {
                    _controller.forward();
                  } else {
                    _controller.reverse();
                  }
                },
                child: Text('Reveal The Secrets'))
          ],
        ),
      ),
    );
  }
}

Use the third plug-in

Writing code from scratch can be cumbersome and time consuming. If you want to get things done quickly and neatly, using the prefabricated widgets in the plug-in is a good choice. The following example uses a great package called flip_card.

Code

1. Add plug-ins to your project:


flutter pub add flip_card

You may need to run:


flutter pub get

Install the plug-in.

2. Implement the FlipCard widget provided by the plug-in:


Center(
        child: FlipCard(
          direction: FlipDirection.HORIZONTAL, 
          front: Container(
            width: 300,
            height: 400,
            color: Colors.red,
          ),
          back: Container(
            width: 300,
            height: 400,
            color: Colors.blue,
          ),
        ),
      ),

Conclusion

We have passed several examples of implementing flipping effects in applications.


Related articles: