
이 코드는 Flutter에서 명시적 애니메이션을 구현하는 방법을 보여줍니다. 명시적 애니메이션은 개발자가 애니메이션의 시작, 종료, 방향 등을 직접 제어할 수 있게 해줍니다. 여기서는 AnimationController와 ColorTween을 사용하여 색상이 변화하는 애니메이션을 만듭니다.
class _ExplicitAnimationsScreenState extends State<ExplicitAnimationsScreen>
with SingleTickerProviderStateMixin {
// AnimationController 선언: 애니메이션의 제어(재생, 정지, 역재생)를 담당합니다.
late final AnimationController _animationController = AnimationController(
vsync: this, // 현재 클래스가 TickerProvider를 제공
duration: const Duration(seconds: 2), // 애니메이션 지속 시간을 2초로 설정
);
// ColorTween을 사용하여 색상을 amber에서 red로 변화시키는 Animation 객체를 생성합니다.
late final Animation<Color?> _color =
ColorTween(begin: Colors.amber, end: Colors.red)
.animate(_animationController); // _animationController에 연결
void _play() {
_animationController.forward(); // 애니메이션을 재생합니다.
}
void _pause() {
_animationController.stop(); // 애니메이션을 일시 정지합니다.
}
void _rewind() {
_animationController.reverse(); // 애니메이션을 역재생합니다.
}
Widget build(BuildContext context) {
print("build");
return Scaffold(
appBar: AppBar(
title: const Text('Explicit Animations'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// AnimatedBuilder를 사용하여 _color Animation에 의해 색상이 변화하는 Container를 구성합니다.
AnimatedBuilder(
animation: _color,
builder: (context, child) {
return Container(
color: _color.value, // _color Animation의 현재 값으로 색상을 설정
width: 400,
height: 400,
);
},
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// 각각의 버튼은 _play, _pause, _rewind 함수를 호출하여 애니메이션을 제어합니다.
ElevatedButton(
onPressed: _play,
child: const Text("Play"),
),
ElevatedButton(
onPressed: _pause,
child: const Text("Pause"),
),
ElevatedButton(
onPressed: _rewind,
child: const Text("Rewind"),
)
],
)
],
),
),
);
}
}
이 코드의 핵심은 ColorTween을 사용하여 시작 색상(Colors.amber)에서 종료 색상(Colors.red)으로 점진적으로 변화하는 애니메이션을 생성하는 것입니다. AnimationController 객체는 이 애니메이션의 재생, 일시 정지, 역재생을 제어합니다. AnimatedBuilder 위젯은 _color 애니메이션의 현재 값을 사용하여 Container의 색상을 업데이트하며, 사용자 인터페이스를 재구성합니다. 이 방법으로, Flutter에서 명시적 애니메이션을 사용하여 동적이고 상호작용적인 사용자 경험을 만들 수 있습니다.