Flutter学习之布局、交互、动画
在Flutter中,可以使用AnimatedContainer
来创建一个带有动画效果的容器。以下是一个简单的例子,展示如何使用AnimatedContainer
来实现容器的尺寸变化和颜色变化:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: MyAnimatedContainer(),
),
),
);
}
}
class MyAnimatedContainer extends StatefulWidget {
@override
_MyAnimatedContainerState createState() => _MyAnimatedContainerState();
}
class _MyAnimatedContainerState extends State<MyAnimatedContainer> {
double _size = 100.0;
Color _color = Colors.blue;
void _changeContainer() {
setState(() {
_size = _size >= 200.0 ? 100.0 : _size + 50.0;
_color = _color == Colors.blue ? Colors.red : Colors.blue;
});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _changeContainer,
child: AnimatedContainer(
duration: Duration(seconds: 2),
curve: Curves.easeIn,
width: _size,
height: _size,
decoration: BoxDecoration(
color: _color,
borderRadius: BorderRadius.circular(10.0),
),
),
);
}
}
这段代码定义了一个名为MyAnimatedContainer
的有状态StatefulWidget
。它包含一个可以通过点击来改变容器大小和颜色的AnimatedContainer
。_changeContainer
方法通过setState
更新容器的状态,触发动画。
评论已关闭