Develop/Flutter

[Flutter] 플러터 AnimatedBuilder 애니메이션 구현

JunJangE 2022. 2. 20. 17:49

이번에는 AnimatedBuilder 애니메이션을 구현해보자.

코드

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

class AnimatedBuilderScreen extends StatefulWidget {
  const AnimatedBuilderScreen({Key? key}) : super(key: key);

  @override
  _AnimatedBuilderScreenState createState() => _AnimatedBuilderScreenState();
}
// TickerProviderStateMixin은 매 프레임마다 함수를 호출하는 객체인데
// 프레임이 변화되어야 할 때 알려주는 거라고 한다.
class _AnimatedBuilderScreenState extends State<AnimatedBuilderScreen>
    with TickerProviderStateMixin {
  

  // 애니메이션을 설정한 Controller
  late final AnimationController _controller = AnimationController(
    duration: const Duration(seconds: 10), // duration 동안 변화
    // vsync 속성에는 TickerProvider를 받는데,
    // 현재 클래스가 상속받은 TikcerProviderStateMixin을 전달하면 된다. 
    // 그래서 vsync:this 로 설정.
    vsync: this,
  )..repeat();
	
  // 앱이 종료되면 Controller로 종료시킨다.
  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Test AnimatedBuilder'),
      ),
      body: Center(
        child: AnimatedBuilder(
          animation: _controller,
          child: Container(
            width: 200.0,
            height: 200.0,
            color: Colors.green,
            child: const Center(
              child: Text(
                'Whee!',
                style: TextStyle(fontSize: 50),
              ),
            ),
          ),
          builder: (BuildContext context, Widget? child) {
            return Transform.rotate(
              angle: _controller.value * 2.0 * math.pi,
              child: child,
            );
          },
        ),
      ),
    );
  }
}

위에서부터 코드를 보게 되면 with을 통해 TickerProviderStateMixin을 오버라이드 하여 기능을 사용하는 것을 볼 수 있는데 TickerProviderStateMixin는 매 프레임마다 함수를 호출하는 객체라고 알면 될 것 같다. 다음으로 애니메이션을 설정할 controller를 작성하여 duration동안 변화하게 한다. 

이제 body 부분에 AnimationBuilder 위젯을 통해 animation은 위에서 작성한 controller 지정하고 child에는 애니메이션을 지정할 위젯을 만든다. builder에는 구현할 애니메이션을 설정한다. 위에는 Transform.rotate를 사용했는데, 이외에도 scale, translate가 더 있다.

 말 그대로 scale은 점점 커지게 것이고 translate은 아래에서 위로, 위에서 아래로 이동시키는 것이다.

scale

builder: (BuildContext context, Widget? child) {
              return Transform.scale(
                scale: _controller.value * 3,
                child: child,
              );
            }),

translate

builder: (BuildContext context, Widget? child) {
              return Transform.translate(
                offset: Offset(0, _controller.value * 600),
                child: child,
              );
            }),

위 코드를 작성하고 실행하면 다음 영상과 같이 실행되는 것을 확인할 수 있다.

참고

 

 

AnimatedBuilder class - widgets library - Dart API

A general-purpose widget for building animations. AnimatedBuilder is useful for more complex widgets that wish to include an animation as part of a larger build function. To use AnimatedBuilder, simply construct the widget and pass it a builder function. F

api.flutter.dev