[flutter] AnimatedBuilder를 이용한 커스텀 애니메이션 구현하기

Flutter 앱을 개발하다 보면 커스텀한 UI 요소나 애니메이션을 구현해야 하는 경우가 있습니다. 이때 AnimatedBuilder를 사용하면 UI를 업데이트하거나 애니메이션을 추가하는 것이 더욱 효율적이고 간편해집니다. 이번 포스트에서는 Flutter의 AnimatedBuilder를 사용하여 커스텀 애니메이션을 어떻게 구현하는지 살펴보겠습니다.

AnimatedBuilder란?

AnimatedBuilder는 애니메이션을 추가하고 UI를 업데이트하는 데 사용되는 위젯입니다. 이 위젯은 주로 AnimationController와 함께 사용되며, 애니메이션을 구현하려는 UI 요소를 AnimatedBuilder 안에 집어넣어 사용합니다. AnimatedBuilder는 자식 위젯을 가지고 있으며, 애니메이션이 발생할 때마다 해당 자식 위젯이 다시 그려지는 원리를 이용합니다.

AnimatedBuilder 사용하기

AnimatedBuilder를 사용하는 방법은 간단합니다. 먼저 AnimationController와 Animation을 초기화한 후, 이들을 사용하여 AnimatedBuilder를 만듭니다. 그런 다음 AnimatedBuilder의 자식으로 애니메이션을 적용하고자 하는 UI 요소를 넣어 줍니다.

AnimationController _controller;
Animation<double> _animation;

@override
void initState() {
  super.initState();
  _controller = AnimationController(
    duration: const Duration(seconds: 2),
    vsync: this,
  );
  _animation = Tween<double>(begin: 0, end: 300).animate(_controller);
  _controller.forward();
}

@override
Widget build(BuildContext context) {
  return AnimatedBuilder(
    animation: _animation,
    builder: (context, child) {
      return Container(
        height: _animation.value,
        width: _animation.value,
        color: Colors.blue,
      );
    },
  );
}

위 예제에서는 AnimatedBuilder를 사용하여 Container의 크기를 애니메이션으로 변경하고 있습니다. AnimatedBuilder는 _animation을 감시하고, 애니메이션이 발생할 때마다 builder를 호출하여 UI를 업데이트합니다.

결론

Flutter의 AnimatedBuilder를 사용하면 커스텀한 애니메이션을 간단하게 구현할 수 있습니다. 애니메이션 처리를 위한 별도의 로직을 작성할 필요 없이 AnimatedBuilder를 활용하여 UI를 업데이트할 수 있기 때문에, 애니메이션 구현이 더욱 쉬워집니다.

AnimatedBuilder의 자세한 내용은 Flutter 공식 문서를 참고하시기 바랍니다.

이상으로 AnimatedBuilder를 이용한 커스텀 애니메이션 구현하기에 대해 알아보았습니다. 감사합니다!