Flutter AnimationController


AnimationController는 Flutter 애니메이션에서 매우 중요한 역할을 하며, 애니메이션의 진행 상태를 제어하는 객체입니다. 이 컨트롤러는 애니메이션의 시작과 끝, 지속 시간, 속도 등을 관리하며, 애니메이션의 상태를 업데이트하고 화면에 반영하는 데 사용됩니다.

1. AnimationController 개요

AnimationControllerAnimation 객체의 값을 생성하고, 애니메이션의 수명주기와 제어를 담당합니다. 애니메이션이 실행되는 동안 애니메이션 값이 어떻게 변화하는지를 정의하고, 이를 통해 애니메이션을 다양한 방식으로 제어할 수 있습니다.

2. 기본 구성 요소

2.1. duration

애니메이션이 완료되는 데 걸리는 시간입니다. Duration 객체로 설정하며, 애니메이션의 전체 길이를 정의합니다.

2.2. vsync

애니메이션의 프레임을 동기화하는 데 사용됩니다. 일반적으로 TickerProvider를 구현한 State 객체를 사용하여 vsync를 제공하며, 이는 애니메이션이 화면의 프레임 속도에 맞춰 업데이트되도록 합니다.

2.3. value

애니메이션의 현재 값을 반환합니다. 애니메이션이 진행됨에 따라 이 값은 변동됩니다.

2.4. forward(), reverse(), repeat(), stop()

애니메이션의 재생 방식과 상태를 제어하는 메서드입니다.

3. 기본 사용 예

3.1. AnimationController 생성 및 초기화

애니메이션 컨트롤러를 생성하려면 AnimationController를 인스턴스화하고 vsyncduration을 설정해야 합니다.

class MyAnimatedWidget extends StatefulWidget {
  @override
  _MyAnimatedWidgetState createState() => _MyAnimatedWidgetState();
}

class _MyAnimatedWidgetState extends State<MyAnimatedWidget> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..repeat(reverse: true); // 애니메이션을 반복하며 역방향으로 재생

    _animation = Tween<double>(begin: 0.0, end: 300.0).animate(_controller);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('AnimationController Demo')),
      body: Center(
        child: AnimatedBuilder(
          animation: _animation,
          builder: (context, child) {
            return Container(
              width: _animation.value,
              height: _animation.value,
              color: Colors.blue,
            );
          },
        ),
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose(); // 컨트롤러 메모리 해제
    super.dispose();
  }
}

4. 주요 메서드 및 속성

4.1. forward()

애니메이션을 시작합니다. 애니메이션이 시작되면 begin 값에서 end 값까지 진행됩니다.

_controller.forward();

4.2. reverse()

애니메이션을 역방향으로 실행합니다. end 값에서 begin 값으로 돌아갑니다.

_controller.reverse();

4.3. repeat()

애니메이션을 반복합니다. reverse: true를 설정하면 애니메이션이 반복하면서 역방향으로도 재생됩니다.

_controller.repeat(reverse: true);

4.4. stop()

애니메이션을 멈춥니다. 현재 애니메이션 값을 유지하며, 재생을 중지합니다.

_controller.stop();

5. 고급 사용

5.1. AnimatedBuilder와 함께 사용

AnimationController를 사용하여 애니메이션을 제어하고, AnimatedBuilder를 사용하여 애니메이션의 상태에 따라 위젯을 빌드합니다. AnimatedBuilder는 애니메이션의 상태를 자동으로 감지하여, 해당 상태에 맞게 UI를 업데이트합니다.

5.2. Tween과 함께 사용

Tween 객체를 사용하여 애니메이션의 시작과 끝 값을 정의하고, AnimationController와 함께 애니메이션을 적용합니다. Tween은 다양한 타입(정수, 실수, 색상 등)을 지원하며, 애니메이션의 값 범위를 정의합니다.

6. 전체 예제 코드

import 'package:flutter/material.dart';

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

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

class MyAnimatedWidget extends StatefulWidget {
  @override
  _MyAnimatedWidgetState createState() => _MyAnimatedWidgetState();
}

class _MyAnimatedWidgetState extends State<MyAnimatedWidget> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..repeat(reverse: true);

    _animation = Tween<double>(begin: 0.0, end: 300.0).animate(_controller);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('AnimationController Demo')),
      body: Center(
        child: AnimatedBuilder(
          animation: _animation,
          builder: (context, child) {
            return Container(
              width: _animation.value,
              height: _animation.value,
              color: Colors.blue,
            );
          },
        ),
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}

이 예제에서는 AnimationControllerTween을 사용하여 애니메이션의 크기를 변동시키는 간단한 예제를 보여줍니다. AnimatedBuilder는 애니메이션의 현재 값에 따라 UI를 업데이트합니다. dispose 메서드에서 AnimationController를 정리하는 것도 중요합니다.

이렇게 AnimationController는 Flutter에서 애니메이션을 효과적으로 제어하고 관리하는 데 필수적인 도구입니다.


Leave a Reply

Your email address will not be published. Required fields are marked *