简介
- AnimatedContainer是Flutter中的一个小部件,用于在动画过程中自动转换容器的属性。通过使用AnimatedContainer,我们可以创建具有动态效果的容器,例如大小、颜色、边框等的变化。
- 即一个样式会变化的Container
使用方法
首先,我们需要导入flutter包:
import 'package:flutter/material.dart';
然后,在构建方法中使用AnimatedContainer小部件:
class MyAnimatedContainer extends StatefulWidget {
@override
_MyAnimatedContainerState createState() => _MyAnimatedContainerState();
}
class _MyAnimatedContainerState extends State<MyAnimatedContainer> {
bool _isExpanded = false;
void _toggleExpanded() {
setState(() {
_isExpanded = !_isExpanded;
});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
_toggleExpanded();
},
child: Center(
child: AnimatedContainer(
duration: Duration(seconds: 1),
curve: Curves.fastOutSlowIn,
width: _isExpanded ? 200.0 : 100.0,
height: _isExpanded ? 200.0 : 100.0,
color: _isExpanded ? Colors.blue : Colors.red,
child: Center(
child: Text(
'Click me!',
style: TextStyle(color: Colors.white),
),
),
),
),
);
}
}
在上面的代码中,我们创建了一个简单的MyAnimatedContainer小部件,其中包含一个AnimatedContainer。当用户点击容器时,容器将以动画效果扩展或缩小,并更改其颜色。
参数说明
- duration:动画持续时间
- curve:动画曲线
- width:容器宽度
- height:容器高度
- color:容器颜色
除了这些参数外,还可以使用其他属性来定制AnimatedContainer的外观和行为。
通过使用AnimatedContainer,我们可以轻松地实现各种动态效果,并为应用增添更多交互性和视觉吸引力。