Flutter学习之布局、交互、动画
warning:
这篇文章距离上次修改已过188天,其中的内容可能已经有所变动。
在Flutter中,我们可以使用AnimatedContainer
来创建一个带有动画效果的容器。以下是一个简单的例子:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: ContainerPage(),
);
}
}
class ContainerPage extends StatefulWidget {
@override
_ContainerPageState createState() => _ContainerPageState();
}
class _ContainerPageState extends State<ContainerPage> {
double _size = 100.0;
Color _color = Colors.red;
bool _change = false;
void _changeContainer() {
setState(() {
_change = !_change;
_size = _change ? 200.0 : 100.0;
_color = _change ? Colors.blue : Colors.red;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Animated Container Example'),
),
body: Center(
child: AnimatedContainer(
duration: Duration(seconds: 2),
curve: Curves.fastOutSlowIn,
width: _size,
height: _size,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color: _color,
),
child: FlatButton(
child: Text('Change Container'),
onPressed: _changeContainer,
),
),
),
);
}
}
在这个例子中,我们创建了一个AnimatedContainer
,它的尺寸和颜色可以在按下按钮时通过_changeContainer
函数更改,并且这个变化是带有动画效果的。我们使用setState
来触发重新构建UI,并且AnimatedContainer
的duration
和curve
属性定义了动画的持续时间和速度。
评论已关闭