注意:無特殊說明,F(xiàn)lutter版本及Dart版本如下:
- Flutter版本: 1.12.13+hotfix.5
- Dart版本: 2.7.0
Flutter中很多用于動(dòng)畫的控件,這篇文章介紹動(dòng)畫控件AnimatedContainer,我們可以通俗的理解AnimatedContainer是帶動(dòng)畫功能的Container,關(guān)于Container的詳細(xì)介紹可以查看Flutter Widgets 之 Container,這篇詳細(xì)介紹了Container的用法。
AnimatedContainer只需要提供動(dòng)畫開始值和結(jié)束值,它就會(huì)動(dòng)起來并不需要我們主動(dòng)調(diào)用setState方法。
變化AnimatedContainer的寬高實(shí)現(xiàn)變大的效果,代碼如下:?
bool click = false;
@override
Widget build(BuildContext context) {
return Center(
child: GestureDetector(
onTap: () {
setState(() {
click = !click;
});
},
child: AnimatedContainer(
height: click ? 200 : 100,
width: click ? 200 : 100,
color: Colors.blue,
duration: Duration(seconds: 3),
),
),
);
}
效果如下:
動(dòng)畫不僅可以作用在寬高上,還可以作用在顏色、邊界、邊界圓角半徑、背景圖片、形狀等。
AnimatedContainer有2個(gè)必須的參數(shù),一個(gè)時(shí)長duration,即動(dòng)畫執(zhí)行的時(shí)長,另一個(gè)是動(dòng)畫曲線curve,默認(rèn)是線性,系統(tǒng)為我們提供了很多動(dòng)畫曲線(加速、減速等)。
設(shè)置動(dòng)畫曲線代碼如下:
AnimatedContainer(
curve: Curves.bounceIn,
...
)
如果想在動(dòng)畫執(zhí)行結(jié)束時(shí)做一些事情,需要設(shè)置onEnd,代碼如下:
AnimatedContainer(
onEnd: (){
...
}
}
實(shí)戰(zhàn)
將圖片放大并過度到圓形,動(dòng)畫執(zhí)行結(jié)束后在反向執(zhí)行動(dòng)畫,如此反復(fù),代碼如下:
AnimatedContainer(
height: click ? 200 : 100,
width: click ? 200 : 100,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(
'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg'),
fit: BoxFit.cover,
),
borderRadius: BorderRadius.all(Radius.circular(
click ? 200 : 0,
))),
duration: Duration(seconds: 3),
curve: Curves.linear,
onEnd: (){
setState(() {
click = !click;
});
},
)
動(dòng)畫效果: