超簡單的Flutter動畫:顏色變換

超簡單的Flutter動畫:顏色變換

Flutter提供了多種動畫實現方式,這篇將實現一個超簡單的顏色變換動畫。

超簡單的Flutter動畫:顏色變換

學習到哪些控件?

  • StatefulWidget
  • Sate
  • SingleTickerProviderStateMixin
  • Animation
  • AnimationController
  • ColorTween

創建“顏色動畫部件”類

  • 創建ColorAnimation.dart
  • 創建ColorAnimation類
class ColorAnimation extends StatefulWidget {
@override
State createState() {
ColorAnimation();
return new _ColorAnimationState();
}
}

創建“顏色動畫狀態”類

  • 創建_ColorAnimationState類
  • 使用時鐘SingleTickerProviderStateMixin
class _ColorAnimationState extends State
with SingleTickerProviderStateMixin {

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

}
@override
Widget build(BuildContext context) {
return null,
);
}
@override
void dispose() {
super.dispose();
}
}
  • 在_ColorAnimationState類中,聲明動畫控制器
AnimationController _controller;
  • 在initState函數中,初始化動畫控制器
_controller = new AnimationController(
vsync: this, duration: new Duration(milliseconds: 1500));
  • 在_ColorAnimationState類中,聲明動畫
Animation animation;
  • 在initState函數中,初始化動畫
  • 這裡使用了“.."語法,它的作用是可以用級聯形式使用對象的成員變量
_animation =
new ColorTween(begin: Colors.blue, end: Colors.red).animate(_controller)
..addListener(() {
setState(() {});
})
..addStatusListener((status) {
if (status == AnimationStatus.completed) {
_controller.reverse();
} else if (status == AnimationStatus.dismissed) {
_controller.forward();
}
});
  • 在initState函數中,正向執行動畫
_controller.forward();
  • 在dispose函數中,釋放動畫控制器資源
void dispose() {
_controller.dispose();
super.dispose();
}
  • 在build函數中,需要動畫的部件
  • 設置width和height
Widget build(BuildContext context) {
return new Center(
child: new Container(
color: _animation.value,
width: 200.0,
height: 200.0,
),
);
}

在main函數中,創建部件

void main() => runApp(MaterialApp(
theme: new ThemeData(primarySwatch: Colors.blue),
home: new Container(
color: Colors.white,
margin: EdgeInsets.all(10.0),
constraints: BoxConstraints.expand(),
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
new Text(
"顏色動畫",

style: new TextStyle(
fontSize: 24.0,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
new Container(
height: 250.0,
child: new ColorAnimation(),
)
],
),
),
));

運行項目

iPhoneXR模擬器效果如下:

超簡單的Flutter動畫:顏色變換

項目地址

[email protected]:hao2008/flutter-demo.git

結語

相比iOS/Android,Flutter提供了更加靈活的動畫實現方式,大家可以多多練習,從單一動畫開始,然後組合動畫,相信大家可以實現出非常有趣的動畫。

下篇預告

超簡單的Flutter動畫:位置變換

歡迎轉發,歡迎收藏,歡迎關注『郝先生談技術』


分享到:


相關文章: