Animations in Flutter

Animations make your app more lively and engaging by adding movement and transitions to UI elements. Flutter provides powerful tools to create smooth animations easily.

Keyword Explanation:

Basic Animation Example: Fading a Widget

Let's animate a simple fade effect where a widget changes its opacity smoothly.

// Import necessary Flutter packages
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FadeDemo(),
    );
  }
}

// StatefulWidget needed because animation changes over time
class FadeDemo extends StatefulWidget {
  @override
  _FadeDemoState createState() => _FadeDemoState();
}

class _FadeDemoState extends State with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation _animation;

  @override
  void initState() {
    super.initState();
    // Create AnimationController with 2 seconds duration
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );

    // Define tween animation from 0 (invisible) to 1 (fully visible)
    _animation = Tween(begin: 0, end: 1).animate(_controller);

    // Start the animation forward
    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose(); // Dispose controller to free resources
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Fade Animation Example')),
      body: Center(
        child: FadeTransition(
          opacity: _animation,
          child: Container(
            width: 200,
            height: 200,
            color: Colors.blue,
            child: Center(
              child: Text(
                'Hello Flutter!',
                style: TextStyle(color: Colors.white, fontSize: 24),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
    
Important Concepts in This Code:

When to Use StatefulWidget Instead of StatelessWidget?

StatelessWidget does not change its appearance after being built. Use it for static UI.

StatefulWidget allows UI to update dynamically, necessary for animations, user input, or data changes.

Real World Analogy

Imagine a curtain slowly opening on a stage. The AnimationController is like the person pulling the curtain at a steady speed, and the Tween is the path the curtain travels from closed to fully open.

More Animation Types

To dive deeper, visit the official Flutter animation docs: Flutter Animations.