[flutter] 플러터에서 useRef 훅(hook)을 사용한 애니메이션 제어

플러터(Flutter) 앱을 개발하다 보면 애니메이션을 다루는데 useRef 훅을 사용하면 매우 유용하다. useRef 훅은 해당 변수가 변경될 때마다 렌더링하지 않고 상태를 유지할 수 있다.

useRef 훅이란?

useRef 훅은 함수형 컴포넌트에서 상태를 유지하고 싶을 때 사용한다. 이 훅을 사용하면 컴포넌트가 렌더링될 때마다 새로운 상태 객체를 생성하지 않고 상태를 유지할 수 있다. 이를 통해 불필요한 렌더링을 방지하고 성능을 향상시킬 수 있다.

플러터에서 useRef 훅 활용하기

다음은 useRef 훅을 사용하여 플러터에서 애니메이션을 제어하는 간단한 예제이다.

import 'package:flutter/material.dart';
import 'dart:math' as math;

void main() {
  runApp(MyApp());
}

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

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

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

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
      duration: Duration(seconds: 1),
      vsync: this,
    );

    _animation = Tween(begin: 0.0, end: 2 * math.pi).animate(_controller);

    _controller.repeat();
  }

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

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

위 예제에서는 AnimationControlleruseRef 훅을 사용하여 애니메이션을 만들고 제어하는 방법을 보여준다.

마치며

이처럼 useRef 훅을 사용하면 플러터 앱에서 애니메이션을 보다 유연하게 제어할 수 있다. useRef를 활용하여 복잡한 애니메이션을 구현하는데 도움이 될 것이다.

참고 자료