카테고리 없음
flutter 코드 모음 - 버튼을 누르면 그림이 360도 회전하는 코드
studyapps
2025. 3. 16. 18:23
앞과 이어지는 코드이다
조금더 업그레이드? 된 코드
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
@override
void initState() {
super.initState();
// AnimationController 설정
_controller = AnimationController(
duration: const Duration(seconds: 5), // 천천히 5초 동안 회전
vsync: this,
);
// CurvedAnimation으로 부드러운 감속 곡선 추가
final curvedAnimation = CurvedAnimation(
parent: _controller,
// curve: Curves.easeInOut,
curve: Curves.easeInCirc,
);
// 0도 ~ 180도 회전 애니메이션 설정
_animation =
Tween<double>(begin: 0.0, end: 2 * pi).animate(curvedAnimation);
}
// 버튼 누를 때 회전 시작
void _startRotation() {
if (_controller.isAnimating) return; // 이미 동작 중이면 무시
_controller.forward(from: 0.0); // 0부터 다시 시작
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('그림 회전 예제'),
leading: const Icon(Icons.image),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('You'),
SizedBox(
child: AnimatedBuilder(
animation: _animation,
builder: (context, child) {
return Transform.rotate(
angle: _animation.value,
child: Image.asset(
'repo/images/img1.png',
),
);
},
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _startRotation,
backgroundColor: Colors.amber,
child: const Icon(Icons.refresh),
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}