⭐
Flutterでクルクル回る星を作る
アニメーションをやってみた!
Flutterでアニメーション機能を使ってみたいなと思い、星のiconがクルクル回る機能を作ってみました。
こちらがデモ
以下に、Flutterで星がクルクル回るアニメーションを作成するためのサンプルコードを提供します。ここでは、Transform.rotateとAnimatedBuilderを使用してアニメーションを作成します。
このコードでは、アイコンを旋回させるアニメーションを作成します。AnimationControllerを使用してアニメーションの持続時間と範囲を定義し、AnimatedBuilderを使用してアニメーションの値が変化するたびにウィジェットを再描画します。
main.dart
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: const Center(
child: RotatingStar(),
),
),
);
}
}
class RotatingStar extends StatefulWidget {
const RotatingStar({Key? key}) : super(key: key);
_RotatingStarState createState() => _RotatingStarState();
}
class _RotatingStarState extends State<RotatingStar>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 2),
)..repeat();
}
void dispose() {
_controller.dispose();
super.dispose();
}
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _controller,
builder: (_, child) {
return Transform.rotate(
angle: _controller.value * 2 * 3.14,
child: child,
);
},
child: const Icon(
Icons.star,
size: 100,
),
);
}
}
まとめ
このコードはRotatingStarというウィジェットを定義しており、このウィジェットはアイコンを回転させます。アイコンは2秒間で360度回転し、アニメーションは無限にリピートします。
Discussion