프로그래밍

[Flutter] 애니메이션 효과 만들기 - AnimationBuilder 위젯

열정 엔지니어 2024. 1. 5. 10:02

AnimationBuilder는 Flutter에서 제공하는 위젯 중 하나로, 애니메이션을 쉽게 구현할 수 있도록 도와줍니다. 이 위젯은 애니메이션의 현재 상태에 따라 어떤 위젯을 화면에 그릴지 결정하는 builder 함수와 애니메이션의 상태를 제어하는 Animation 객체를 인자로 받습니다. AnimationBuilder의 사용법은 다음과 같습니다:

  1. 먼저, AnimationController를 생성합니다. AnimationController는 애니메이션의 진행 상태를 제어하는 역할을 합니다.이 컨트롤러는 애니메이션의 시작, 종료, 방향 등을 제어할 수 있습니다. 컨트롤러 인스턴스 할당은 initState(){} 함수 안에서 해줍니다.
late AnimationController _controller;

_controller = AnimationController(
  duration: const Duration(milliseconds: 500),
  vsync: this,
)..repeat(reverse: true);
  1. 그 다음, AnimationBuilder 위젯을 사용하여 애니메이션을 구현합니다. AnimationBuilder는 animation 속성에 AnimationController를 전달받고, builder 속성에는 애니메이션의 현재 상태에 따라 화면에 그릴 위젯을 반환하는 함수를 전달받습니다.
AnimatedBuilder(  
animation: _controller,  
builder: (context, child) {  
// 여기에 애니메이션의 현재 상태에 따라 그릴 위젯을 반환하는 코드를 작성합니다.  
},  
);
  1. builder 함수 내에서는 animation의 현재 값을 사용하여 애니메이션 효과를 적용할 수 있습니다. 예를 들어, Transform.translate 위젯을 사용하여 _controller.value에 따라 위젯을 이동시킬 수 있습니다.
AnimatedBuilder(
  animation: _controller,
  builder: (context, child) {
    return Transform.translate(
      offset: Offset(0, _controller.value),
      // 여기에 이동할 위젯을 작성합니다.
    );
  },
);

이렇게 AnimationBuilder를 사용하면 복잡한 애니메이션 로직 없이도 다양한 애니메이션 효과를 쉽게 구현할 수 있습니다.

반응형