상세 컨텐츠

본문 제목

버튼 클릭 시 색상 변화 애니메이션 구현하기

공부/Flutter

by micalcomanie 2025. 1. 3. 13:16

본문

728x90
반응형
SMALL

Flutter는 애니메이션 기능을 통해 사용자 경험(UX)을 개선할 수 있습니다.
이 글에서는 Flutter에서 버튼 클릭 시 색상이 부드럽게 변하는 애니메이션을 구현하는 방법을 단계별로 설명합니다.


1. 목표

  • 버튼을 클릭할 때 색상이 부드럽게 전환되는 애니메이션 구현.
  • Flutter의 기본 애니메이션 도구를 활용하여 직관적으로 개발.

2. Flutter 프로젝트 설정

Flutter 프로젝트를 설정하고 애니메이션을 구현하기 위한 준비 과정을 진행합니다.

2.1 Flutter 프로젝트 생성

터미널에서 다음 명령어를 실행하여 새 프로젝트를 생성합니다:

flutter create color_animation_button
cd color_animation_button

2.2 필수 패키지

추가 패키지 없이 기본 Flutter 환경에서 진행합니다.


3. 구현 단계

3.1 기본 코드 구조

main.dart 파일에 기본 구조를 작성합니다:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Button Color Animation',
      home: ColorAnimationButton(),
    );
  }
}

3.2 애니메이션 구현

ColorAnimationButton 위젯을 작성하여 색상 변화 애니메이션을 구현합니다:

class ColorAnimationButton extends StatefulWidget {
  @override
  _ColorAnimationButtonState createState() => _ColorAnimationButtonState();
}

class _ColorAnimationButtonState extends State<ColorAnimationButton>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<Color?> _colorAnimation;

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

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

    _colorAnimation = ColorTween(
      begin: Colors.blue,
      end: Colors.red,
    ).animate(_controller);
  }

  void _onButtonPressed() {
    if (_controller.status == AnimationStatus.completed) {
      _controller.reverse();
    } else {
      _controller.forward();
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Color Animation Button'),
      ),
      body: Center(
        child: AnimatedBuilder(
          animation: _colorAnimation,
          builder: (context, child) {
            return ElevatedButton(
              style: ElevatedButton.styleFrom(
                primary: _colorAnimation.value,
                padding: EdgeInsets.symmetric(horizontal: 30, vertical: 15),
              ),
              onPressed: _onButtonPressed,
              child: Text(
                'Press Me',
                style: TextStyle(color: Colors.white, fontSize: 18),
              ),
            );
          },
        ),
      ),
    );
  }
}

4. 코드 설명

  • AnimationController: 애니메이션의 시작, 정지, 반전 등의 상태를 제어합니다.
    • duration: 애니메이션이 완료되는 시간.
  • ColorTween: 시작 색상과 끝 색상을 정의하여 색상 전환을 구현합니다.
  • AnimatedBuilder: 애니메이션 상태가 변경될 때마다 UI를 다시 빌드합니다.
  • _onButtonPressed(): 버튼 클릭 시 애니메이션의 방향을 전환합니다.

5. 실행 결과

  1. 버튼의 초기 색상은 파란색(blue)입니다.
  2. 버튼을 클릭하면 빨간색(red)으로 부드럽게 변합니다.
  3. 다시 클릭하면 파란색으로 돌아옵니다.

6. 추가 개선 아이디어

  • 다양한 효과 추가: 색상 변화와 함께 버튼의 크기 변화 또는 회전 효과를 추가.
  • 사용자 설정: 사용자 입력에 따라 색상 및 애니메이션 속도를 동적으로 변경.
  • 상태 관리: Provider 또는 Riverpod를 사용하여 상태를 전역적으로 관리.

7. 결론

Flutter의 애니메이션 기능은 간단한 동작으로도 UX를 크게 향상시킬 수 있습니다. 위 예제를 바탕으로 더욱 다양한 애니메이션을 구현해 보세요. 다음 글에서는 여러 애니메이션을 조합하는 방법을 다룰 예정입니다.


참고 자료

728x90
반응형
LIST

관련글 더보기