Flutter Widget 之TweenAnimationBuilder

371 阅读1分钟

你想要一个简单的动画,但是没有一个内置的隐式动画widget能解决问题? TweenAnimationBuilder可以满足您对所有自定义动画的需求而不必担心讨人厌的动画控制器

ezgif.com-gif-maker (3).gif

1、TweenAnimationBuilder很容易上手,使用duration参数设置希望动画云心烦的时间长度,

2、然后,添加builder方法来绘制动画的widget。第二个参数类型取决于要在widget中设置动画的内容,在这种情况下,它将保存我们要应用于ColorFilter的任何“颜色“值

3、最后,使用tween参数指定要设置动画的值,如果您有指定tween的类型,它应与builder中第二个参数的类型以及类型参数相匹配

TweenAnimationBuilder<Color>(
    duration: const Duration(second: 3),
    tween: ColorTween(begin: Colors.white, end: Colors.orange),
    builder: (BuildContext _, Color value, Widget __){
        return ColorFiltered(
            child: DashWidget(),
            colorFilter: ColorFilter.mode(value, BlendMode.modulate),
        );
    };
)

ezgif.com-gif-maker.gif

若要修改一个值到另一个值的动画制作方式,您可以设置曲线参数

TweenAnimationBuilder<Color(
    duration: const Duration(second: 3),
    tween: ColorTween(
        begin: Colors.white,
        end: Colors.orange,
    ),
    curve: Curves.bounceInOut,
    builder: (BuilderContext _, Color value, Widget __){...},
)

ezgif.com-gif-maker (1).gif

添加onEnd参数,在动画完成时得到通知

TweenAnimcationBuilder<Color>(
    duration: const Duration(seconds: 3),
    tween: ColorTween(
        begin: Colors.white,
        end: Colors.orange,
    ),
    builder: (BuildContext _, Color value, Widget __){...},
    onEnd: () => print('all done!'),
),

你甚至可以使用它来设置新值并再次设置动画

// ElseWhere in the code:
Color _colorValue = Colors.orange;


TweenAnimationBuilder<Color>(
   duration: const Duration(seconds: 3),
   tween: ColorTween(
       beginL Colors.white,
       end: _colorValuem
   ),
   builder: (BuilderContext _, Color value, Widget __){...},
   onEnd: () => setState(
                   () => _colorValue = Colors.green
               ),
),

ezgif.com-gif-maker (2).gif

最后,为了优化性能,您可以传入一个child,使FLutter 不需要在动画过程中不需要重建整个窗口widget树

TweenAnimationBuilder<Color>(
    duration: const Duration(seconds: 3),
    tween: ColorTween(
        begin: Colors.white,
        end: Colors.orange,
    ),
    child: DashWidget(),
    builder: (BuildContext _, Color value, Widget child){
        return ColorFiltered(
            child: child,
            colorFilter: ColorFilter.mode(
                valuem BlendMode.modulate,
            ),
        );
    },
)

如果想了解有关TweenAnimationBuilder 的内容,或者关于Flutter的其他功能,请访问flutter.dev

原文翻译自视频:视频地址