CamKode

Creating a Heart Animation in Flutter

Avatar of Kosal Ang

Kosal Ang

Mon Jul 01 2024

Creating a Heart Animation in Flutter

Animations can significantly enhance the user experience in mobile applications. One common animation is the heart (love) animation, which is often used to indicate a "like" or "favorite" action. In this article, we'll walk through how to implement a heart animation in Flutter that scales and changes color when pressed.

Prerequisites

Before we start, ensure you have the following:

  • Flutter installed on your machine.
  • Basic understanding of Flutter widgets and animations.

Step-by-Step Guide

Step 1: Setting Up the Project

Create a new Flutter project or open an existing one. In the lib directory, create a new file named heart_animation.dart.

1import 'package:flutter/material.dart';
2
3void main() {
4  runApp(MyApp());
5}
6
7class MyApp extends StatelessWidget {
8  
9  Widget build(BuildContext context) {
10    return MaterialApp(
11      home: Scaffold(
12        appBar: AppBar(
13          title: Text('Heart Animation Example'),
14        ),
15        body: Center(
16          child: HeartAnimation(),
17        ),
18      ),
19    );
20  }
21}
22

Step 2: Creating the HeartAnimation Widget

In the heart_animation.dart file, define a new stateful widget named HeartAnimation. This widget will contain the animation logic.

1class HeartAnimation extends StatefulWidget {
2  
3  _HeartAnimationState createState() => _HeartAnimationState();
4}
5
6class _HeartAnimationState extends State<HeartAnimation> with SingleTickerProviderStateMixin {
7  late AnimationController _controller;
8  late Animation<double> _scaleAnimation;
9  late Animation<Color?> _colorAnimation;
10  bool _isLiked = false;
11
12  
13  void initState() {
14    super.initState();
15    _controller = AnimationController(
16      vsync: this,
17      duration: Duration(milliseconds: 300),
18    );
19
20    _scaleAnimation = TweenSequence([
21      TweenSequenceItem(tween: Tween(begin: 1.0, end: 1.3).chain(CurveTween(curve: Curves.easeIn)), weight: 50),
22      TweenSequenceItem(tween: Tween(begin: 1.3, end: 1.0).chain(CurveTween(curve: Curves.easeOut)), weight: 50),
23    ]).animate(_controller);
24
25    _colorAnimation = ColorTween(begin: Colors.grey, end: Colors.red).animate(_controller);
26  }
27
28  
29  void dispose() {
30    _controller.dispose();
31    super.dispose();
32  }
33
34  void _handleTap() {
35    if (_isLiked) {
36      _controller.reverse();
37    } else {
38      _controller.forward();
39    }
40    setState(() {
41      _isLiked = !_isLiked;
42    });
43  }
44
45  
46  Widget build(BuildContext context) {
47    return GestureDetector(
48      onTap: _handleTap,
49      child: AnimatedBuilder(
50        animation: _controller,
51        builder: (context, child) {
52          return Transform.scale(
53            scale: _scaleAnimation.value,
54            child: Icon(
55              Icons.favorite,
56              color: _colorAnimation.value,
57              size: 100,
58            ),
59          );
60        },
61      ),
62    );
63  }
64}
65

Step 3: Integrating the Animation

In the main lib/main.dart file, import the heart_animation.dart file and use the HeartAnimation widget.

1import 'package:flutter/material.dart';
2import 'heart_animation.dart'; // Adjust the import based on your file structure
3
4void main() {
5  runApp(MyApp());
6}
7
8class MyApp extends StatelessWidget {
9  
10  Widget build(BuildContext context) {
11    return MaterialApp(
12      home: Scaffold(
13        appBar: AppBar(
14          title: Text('Heart Animation Example'),
15        ),
16        body: Center(
17          child: HeartAnimation(),
18        ),
19      ),
20    );
21  }
22}
23

Explanation

  • AnimationController: Manages the animation.
  • TweenSequence: Defines a sequence of tweens for scaling the heart icon. It scales up and then back to its original size.
  • ColorTween: Animates the color change from grey to red.
  • AnimatedBuilder: Rebuilds the widget when the animation changes.
  • GestureDetector: Detects taps to start or reverse the animation.

Customization

You can adjust the following parameters to customize the animation:

  • Duration: Change the duration in the AnimationController for faster or slower animations.
  • Colors: Modify the ColorTween to use different colors.
  • Scale: Adjust the scaling values in the TweenSequence for larger or smaller scaling effects.

Conclusion

By following this guide, you have successfully created a heart animation in Flutter. This animation scales the heart icon and changes its color when tapped, providing a visually appealing effect for users. Feel free to customize the animation to better suit your application's design and requirements.

Related Posts

Dart nested Map getter/setter

Dart nested Map getter/setter

Get and Set your nested Map without converting them to a model mapped version. Just use the key path to go directly where you want and get, set keys and values.

© 2024 CamKode. All rights reserved

FacebookTwitterYouTube