[flutter] velocity_x를 사용하여 어떻게 스택 애니메이션을 만들 수 있는가?

Flutter는 강력한 UI 툴킷이며, velocity_x 패키지는 다양한 위젯과 애니메이션을 쉽게 구현할 수 있는 도구입니다. 이번 예제에서는 velocity_x를 사용하여 스택 애니메이션을 만드는 방법에 대해 알아보겠습니다.

velocity_x 패키지 설치하기

먼저 pubspec.yaml 파일에 velocity_x 패키지를 추가해야 합니다.

dependencies:
  flutter:
    sdk: flutter
  velocity_x: ^1.2.1

패키지를 추가한 후, 터미널에서 flutter pub get 명령어를 통해 패키지를 설치합니다.

스택 애니메이션 구현하기

  1. 먼저, VelocityX 패키지를 import합니다.
import 'package:velocity_x/velocity_x.dart';
  1. 애니메이션을 적용할 위젯을 생성합니다. 여기서는 간단한 스택 위젯을 사용하도록 하겠습니다.
Widget animatedStack() {
  return VStack([
    "Stack".text.xl4.bold.make(),
    HStack([
      "Item 1".text.lg.make().box.color(Vx.red500).p16.square(100).make().p4(),
      "Item 2".text.lg.make().box.color(Vx.green500).p16.square(100).make().p4(),
      "Item 3".text.lg.make().box.color(Vx.blue500).p16.square(100).make().p4(),
    ]).box.make().p12().wh300(context),
  ]);
}
  1. 애니메이션을 적용할 스택 위젯을 VelocityX의 VelocityXAnimate 위젯으로 감싸줍니다. 이 위젯은 자식 위젯에 애니메이션 효과를 부여합니다. 아래 코드에서는 VelocityXAnimate()spring 매개변수를 사용하여 애니메이션의 스프링 효과를 설정합니다.
Widget animatedStack() {
  return VelocityXAnimate(
    spring: const Duration(milliseconds: 500),
    child: VStack([
      "Stack".text.xl4.bold.make(),
      HStack([
        "Item 1".text.lg.make().box.color(Vx.red500).p16.square(100).make().p4(),
        "Item 2".text.lg.make().box.color(Vx.green500).p16.square(100).make().p4(),
        "Item 3".text.lg.make().box.color(Vx.blue500).p16.square(100).make().p4(),
      ]).box.make().p12().wh300(context),
    ]),
  );
}
  1. 애니메이션 효과를 보기 위해 위젯을 GestureDetector로 감싸 기능을 추가합니다. 아래 코드에서는 onTap 이벤트가 발생할 때마다 스택 위젯이 회전하도록 구현하였습니다.
Widget animatedStack() {
  double _rotation = 0;

  return GestureDetector(
    onTap: () {
      _rotation += 0.5;
      setState(() {});
    },
    child: VelocityXAnimate(
      spring: const Duration(milliseconds: 500),
      child: VStack([
        "Stack".text.xl4.bold.make(),
        HStack([
          "Item 1".text.lg.make().box.color(Vx.red500).p16.square(100).make().p4(),
          "Item 2".text.lg.make().box.color(Vx.green500).p16.square(100).make().p4(),
          "Item 3".text.lg.make().box.color(Vx.blue500).p16.square(100).make().p4(),
        ]).box.make().p12().wh300(context),
      ]).rotateZ(_rotation),
    ),
  );
}
  1. 마지막으로, 해당 위젯을 앱에 추가하고 테스트합니다.
class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Animated Stack"),
      ),
      body: Center(
        child: animatedStack(),
      ),
    );
  }
}

위와 같이 코드를 작성하고 앱을 실행하면, 탭을 할 때마다 스택 위젯이 부드럽게 회전하는 애니메이션을 확인할 수 있습니다.

참고 자료