Flutter 中的 Animations(二)

官方文档android

AnimatedWidget

还记得 上一节 里面是怎么更新 widget 的状态的吗?咱们上次的步骤是:首先建立动画,而后给动画添加监听 addListener(...), 在 addListener(...) 方法中咱们干了件 很重要 的事儿:setState((){}),由于只有调用这个,才会让 widget 重绘。git

这一次咱们使用 AnimatedWidget 来实现动画,使用它就不须要给动画 addListener(...)setState((){}) 了,AnimatedWidget 本身会使用当前 Animationvalue 来绘制本身。固然,这里 Animation 咱们是以构造参数的方式传递进去的。github

看代码:markdown

class AnimatedContainer extends AnimatedWidget {

  AnimatedContainer({Key key, Animation<double> animation})
      : super (key: key, listenable: animation);

  @override
  Widget build(BuildContext context) {
    final Animation<double> animation = listenable;
    return Center(
      child: Container(
        decoration: BoxDecoration(
            color: Colors.redAccent
        ),
        margin: EdgeInsets.symmetric(vertical: 10.0),
        height: animation.value,
        width: animation.value,
      ),
    );
  }
}
复制代码

上述代码中,咱们定义了一个 AnimatedContainer 继承了 AnimatedWidget,而后定义了一个构造方法,注意,构造方法中咱们定义了一个 Animation 而后把这个 Animation 传到父类(super)中去了,咱们能够看看 listenable: animation 这个参数,是一个 Listenable 类型,以下:app

/// The [Listenable] to which this widget is listening.
///
/// Commonly an [Animation] or a [ChangeNotifier].
final Listenable listenable;
复制代码

而后再看看 Animation 类:dom

abstract class Animation<T> extends Listenable implements ValueListenable<T> {
...
}
复制代码

能够看到 AnimationListenable 的子类,因此在咱们自定义的 AnimatedContainer 类中能够传一个 Animation 类型的的参数做为父类中 listenable 的值。ide

使用咱们上面定义的 AnimatedContainer 也很简单,直接做为 widget 使用就好,部分代码以下:post

@override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AnimatedWidgetDemo',
      theme: ThemeData(
          primaryColor: Colors.redAccent
      ),
      home: Scaffold(
          appBar: AppBar(
            title: Text('AnimatedWidgetDemo'),
          ),
          body: AnimatedContainer(animation: animation,)
      ),
    );``
  }
复制代码

能够看出咱们在实例化 AnimatedContainer 的时候传入了一个 Animation 对象。动画

AnimatedWidgetDemo.dartui

效果以下:

AnimatedBuilder

咱们先看看如何使用 AnimatedBuilder 作一个上面同样的效果

部分代码以下:

@override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AnimatedBuilderExample',
      theme: ThemeData(primaryColor: Colors.redAccent),
      home: Scaffold(
        appBar: AppBar(
          title: Text('animatedBuilderExample'),
        ),
        body: Center(
          child: AnimatedBuilder(
            animation: _animation,
            child: Container(
              decoration: BoxDecoration(color: Colors.redAccent),
            ),
            builder: (context, child) {
              return Container(
                width: _animation.value,
                height: _animation.value,
                child: child,
              );
            },
          ),
        ),
      ),
    );
  }
复制代码

由于 AnimatedBuilder 是继承于 AnimatedWidget 的,

class AnimatedBuilder extends AnimatedWidget { ... }
复制代码

因此能够直接把 AnimatedBuilder 看成 widget 使用

上述代码关键部分以下:

body: Center(
  child: AnimatedBuilder(
    animation: _animation,
    child: Container(
      decoration: BoxDecoration(color: Colors.redAccent),
    ),
    builder: (context, child) {
      return Container(
        width: _animation.value,
        height: _animation.value,
        child: child,
      );
    },
  ),
),
复制代码

效果以下:

AnimatedBuilderExample_2.dart

builder 这个匿名类是每次动画值改变的时候就会被调用

AnimatedBuilder 使用简化后的结构以下:

AnimatedBuilder(
    animateion: ... ,
    child: ... ,
    builder: (context, child) {
        return Container(
            width: ... ,
            height: ... ,
            child: child
        )
    }
)
复制代码

上述代码看着可能会有迷糊的地方,里面的 child 好像被指定了两次,外面一个,里面一个。其实,外面的 child 是传给 AnimatedBuilder 的,而 AnimatedBuilder 又将这个 child 做为参数传递给了里面的匿名类(builder)。

咱们能够验证上述说明,就是给外面的 child 指定一个 key,而后在 builder 里面打印出参数 childkey

body: Center(
  child: AnimatedBuilder(
    animation: _animation,
    child: Container(
      decoration: BoxDecoration(color: Colors.redAccent),
    key: Key("android"),
    ),
    builder: (context, child) {
      print("child.key: ${child.key}");
      return Container(
        width: _animation.value,
        height: _animation.value,
        child: child,
      );
    },
  ),
),
复制代码

咱们在外面的 child 里面的添加了一个 key 值,而后在 builder 里面打印出参数 childkey

输出以下:

flutter: child.key: [<'android'>]
复制代码

区别

咱们来看看 AnimatedBuilder AnimatedWidget 和添加 addListener{}监听并在里面触发 setState(...) 这三种方式作动画有什么区别。

为了更直观的看出它们的区别,这里使用一个第三方控件:RandomContainer,这个控件会在屏幕每次重绘的时候改变自身的颜色。

首先在pubspec.yaml中添加依赖 random_pk: any,以下:

dependencies:
 flutter:
 sdk: flutter
 cupertino_icons: ^0.1.2
  # RandomContainer
 random_pk: any
复制代码

先写一个小例子来看看 RandomContainer 这个控件每次在屏幕重绘的时候自身颜色改变的状况。

在屏幕上绘制一个宽高都为200.0RandomContainer 而后给 RandomContainer 添加点击事件,点击事件里面作的就是调用 setState(...)widget 重绘,部分代码以下:

body: Center(
  child: GestureDetector(
    onTap: _changeColor,
    child: RandomContainer(
      width: 200.0,
      height: 200.0,
    ),
  ),
),
复制代码

使用 RandomContainer 的时候须要引入 import 'package:random_pk/random_pk.dart';

点击事件代码以下:

void _changeColor() {
    setState(() {});
  }
复制代码

AnimatedBuilderExample_1.dart

效果以下:

接下来咱们使用三种方式实现同一种效果来看看有什么不一样:

AnimatedWidget

_controller =
        AnimationController(vsync: this, duration: Duration(seconds: 5))
          ..repeat();
复制代码
@override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AnimatedBuilder',
      theme: ThemeData(primaryColor: Colors.redAccent),
      home: Scaffold(
        appBar: AppBar(
          title: Text('AnimatedBuilder'),
        ),
        body: Center(
          child: RandomContainer(
            width: 200.0,
            height: 200.0,
            child: AnimatedWidgetDemo( // new
              animation: _controller,
            ),
          ),
        ),
      ),
    );
  }
复制代码

效果以下:

AnimatedBuilder

_controller =
        AnimationController(vsync: this, duration: Duration(seconds: 5))
          ..repeat();
复制代码
@override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AnimatedBuilder',
      theme: ThemeData(primaryColor: Colors.redAccent),
      home: Scaffold(
        appBar: AppBar(
          title: Text('AnimatedBuilder'),
        ),
        body: Center(
          child: RandomContainer(
            width: 200.0,
            height: 200.0,
            child: AnimatedBuilderDemo( // new
              child: getContainer(),
              animation: _controller,
            ),
          ),
        ),
      ),
    );
  }
复制代码

AnimatedBuilder 的效果和 AnimatedWidget 的效果是同样的。

接下来咱们看看在 addListener{} 里面调用 setState(...) 的效果,也就是咱们在上一节中实现动画的方式

_controller =
        AnimationController(vsync: this, duration: Duration(seconds: 5))
          ..repeat()
          ..addListener(() {
            setState(() {});
          });
复制代码
@override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AnimatedBuilder',
      theme: ThemeData(primaryColor: Colors.redAccent),
      home: Scaffold(
        appBar: AppBar(
          title: Text('AnimatedBuilder'),
        ),
        body: Center(
          child: RandomContainer(
            width: 200.0,
            height: 200.0,
            child: Transform.rotate( // new
              child: getContainer(),
              angle: _controller.value * 2.0 * pi,
            ),
          ),
        ),
      ),
    );
  }
复制代码

效果以下

看出来了吧。。。

AnimatedBuilderExample_3.dart

RandomContainer 参考

若有错误,还请指出,谢谢!

相关文章
相关标签/搜索