AnimatedSwitcher
好久没写博客了,今天写一个新学的Widget:AnimatedSwitcher
其构造函数如下:
const AnimatedSwitcher({ Key key, this.child, @required this.duration, this.reverseDuration, this.switchInCurve = Curves.linear, this.switchOutCurve = Curves.linear, this.transitionBuilder = AnimatedSwitcher.defaultTransitionBuilder, this.layoutBuilder = AnimatedSwitcher.defaultLayoutBuilder, })
该组件可以达到如下图所示的效果:
该组件能够动态切换一个child的不同形态,适用于点击样式的转变/Tab切换等待
child为实际显示的Widget;
duration:动画持续时间;
reverseDuration:一般不指定,默认和duration一样;
两个curve不说了;
transitionBuilder:切换动画builder,签名是:
Widget Function(Widget child, Animation<double> animation);
layoutBuilder:定位子组件位置的函数,签名:
Widget Function(Widget currentChild, List<Widget> previousChildren);
例子:
class _MyHomePageState extends State<MyHomePage> { Color color = Colors.red; var cont = Container(key: ValueKey(1), color: Colors.red, width: 50, height: 45,); @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ FlatButton(child: Text('点我'), onPressed: () {setState(() { if (color == Colors.red) { cont = Container(key: ValueKey(2), color: Colors.green, width: 50, height: 45,); color = Colors.green; } else { cont = Container(key: ValueKey(1), color: Colors.red, width: 50, height: 45,); color = Colors.red; } });},), SizedBox(height: 50,), AnimatedSwitcher( duration: Duration(milliseconds: 500), child: cont, transitionBuilder: (child, animation) { return ScaleTransition( child: child, scale: animation.drive(Tween(begin: 0, end: 1)), ); }, ), ], ), ), ); } }
上面代码中的TransitionBuilder参数使用了ScaleTransition,是切换大小的效果,也可以使用fadetransition(渐变效果)等其它切换效果。
进击的小🐴农