Flutter圈子程序员Flutter教程网

新贵 Flutter (8)动画

2019-06-22  本文已影响30人  zidea
flutter

我们都知道 Container (容器)组件提供一些用于定义高度、宽度、背景色、内边距以及边框等属性。在实际开发中可以通过随着时间改变这些属性的值来达到动画效果。

为了这一目的 Flutter 提供了一个特殊 AnimatedContainer 容器用于对这些属性进行动画。在 Flutter 中会根据您修改的值进行动画,无需我们显式进行配置便可以得到很好的动画效果。

This recipe describes how to use an AnimatedContainer to animate the size, background color, and border radius when the user taps a button using the following steps:

  1. 使用默认配置来创建一个 StatefulWidget
class AnimatedContainerApp extends StatefulWidget{

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _AnimatedContainerAppState();
  }

}

class _AnimatedContainerAppState extends State<AnimatedContainerApp>{
  double _width = 50;
  double _height = 50;

  Color _color = Colors.green;
  BorderRadiusGeometry _radiusGeometry = BorderRadius.circular(8);
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home:Scaffold(
        appBar: AppBar(
          title: Text("动画效果"),
        ),
        body: Center(
          child: Text("动画效果"),
        ),
      )
    );
  }

}
  1. 使用这些属性定义一个 AnimatedContainer
class _AnimatedContainerAppState extends State<AnimatedContainerApp> {
  double _width = 50;
  double _height = 50;

  Color _color = Colors.green;
  BorderRadiusGeometry _borderRadius = BorderRadius.circular(8);
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: Text("动画效果"),
      ),
      body: Center(
          child: AnimatedContainer(
            width: _width,
        height: _height,
        decoration: BoxDecoration(color: _color,borderRadius: _borderRadius),
        duration: Duration(seconds: 1),
        curve: Curves.fastOutSlowIn,
      )),
    ));
  }
}
  1. 通过为 AnimatedContainer 重新赋值来
          floatingActionButton: FloatingActionButton(onPressed: (){
            setState(() {
              final random = Random();
              _width = random.nextInt(120).toDouble();
              _height = random.nextInt(120).toDouble();

              _color = Color.fromARGB(random.nextInt(256), random.nextInt(256), random.nextInt(256), 1);
              _borderRadius = BorderRadius.circular(random.nextInt(100).toDouble());
            });
          }),
上一篇下一篇

猜你喜欢

热点阅读