どうも、ちょげ(@chogetarou)です。
フェードアニメーションをする方法を紹介します。
方法

フェードアニメーションをするには、FadeTransitionウェジェットを使います。
準備
まず、アニメーション関連の変数を用意します。
late AnimationController _controller;
late Animation<double> _fadeAnimation;
次に、これらの変数を「initState」で初期化します。
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: Duration(seconds: 2),
vsync: this,
);
_controller.addListener(() {
setState(() {});
print(_controller.value);
});
_fadeAnimation = CurvedAnimation(parent: _controller, curve: Curves.easeIn);
}
そして、disposeでは、AnimationControllerの破棄をします。
@override
void dispose() {
super.dispose();
_controller.dispose();
}
最後にアニメーションを操作するための関数を用意します。
void _animationChange() {
if (_controller.status == AnimationStatus.completed) {
_controller.reverse();
} else {
_controller.forward();
}
}
これでアニメーションをするための準備が出来ました。
アニメーション
FadeTransitionにアニメーションの設定をします。
FadeTransition(
opacity: _fadeAnimation,
child: Container(
height: 100,
width: 100,
color: Colors.blue,
),
),
あとは、タップやスワイプなどのトリガーに用意した関数を指定します。
TextButton(
onPressed: _animationChange,
child: Text('Switch!'),
)
これでフェードアニメーションが出来るようになります。
使用例
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
FadeTransition(
opacity: _fadeAnimation,
child: Container(
height: 100,
width: 100,
color: Colors.blue,
),
),
TextButton(
onPressed: _animationChange,
child: Text('Switch!'),
)
],
));
}
使用したコード
class Sample extends StatefulWidget {
@override
_SampleState createState() => _SampleState();
}
class _SampleState extends State<Sample> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _fadeAnimation;
void _animationChange() {
if (_controller.status == AnimationStatus.completed) {
_controller.reverse();
} else {
_controller.forward();
}
}
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: Duration(seconds: 2),
vsync: this,
);
_controller.addListener(() {
setState(() {});
print(_controller.value);
});
_fadeAnimation = CurvedAnimation(parent: _controller, curve: Curves.easeIn);
}
@override
void dispose() {
super.dispose();
_controller.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
FadeTransition(
opacity: _fadeAnimation,
child: Container(
height: 100,
width: 100,
color: Colors.blue,
),
),
TextButton(
onPressed: _animationChange,
child: Text('Switch!'),
)
],
));
}
}
コメント