当子组件变化时执行动画,需要指定子组件的key进行标识。动画方式可以自定义,能指定动画时长、动画曲线等属性。

相关组件

AnimatedCrossFade

AnimatedSwitcher基本使用

  1. <br />【child】 : 孩子组件 【Widget】<br />【duration】 : 动画时长 【Duration】<br />【switchOutCurve】 : 切出曲线 【Curves】<br />【switchInCurve】 : 切入曲线 【Curves】<br />【switchInCurve】 : 切入曲线 【Curves】<br />【transitionBuilder】 : 动画构造器 【Widget Function(Widget, Animation<double>)】<br />![108.gif](https://cdn.nlark.com/yuque/0/2020/gif/326147/1589449310712-630a1245-5047-4df5-ab20-560687248523.gif#align=left&display=inline&height=119&margin=%5Bobject%20Object%5D&name=108.gif&originHeight=119&originWidth=403&size=164995&status=done&style=none&width=403)
  1. import 'package:flutter/material.dart';
  2. class CustomAnimatedSwitcher extends StatefulWidget {
  3. @override
  4. _CustomAnimatedSwitcherState createState() => _CustomAnimatedSwitcherState();
  5. }
  6. class _CustomAnimatedSwitcherState extends State<CustomAnimatedSwitcher> {
  7. int _count = 0;
  8. @override
  9. Widget build(BuildContext context) {
  10. return Container(
  11. child: Wrap(
  12. crossAxisAlignment: WrapCrossAlignment.center,
  13. children: <Widget>[
  14. _buildMinusBtn(),
  15. SizedBox(width:80,child: _buildAnimatedSwitcher(context)),
  16. _buildAddBtn()
  17. ],
  18. ),
  19. );
  20. }
  21. Widget _buildAnimatedSwitcher(BuildContext context) =>
  22. AnimatedSwitcher(
  23. duration: const Duration(milliseconds: 400),
  24. transitionBuilder: (Widget child, Animation<double> animation) =>
  25. ScaleTransition(
  26. child: RotationTransition(turns: animation, child: child),
  27. scale: animation),
  28. child: Text(
  29. '$_count',
  30. key: ValueKey<int>(_count),
  31. style: Theme.of(context).textTheme.display3,
  32. ),
  33. );
  34. Widget _buildMinusBtn() {
  35. return MaterialButton(
  36. padding: EdgeInsets.all(0),
  37. textColor: Color(0xffFfffff),
  38. elevation: 3,
  39. color: Colors.red,
  40. highlightColor: Color(0xffF88B0A),
  41. splashColor: Colors.red,
  42. child: Icon(
  43. Icons.remove,
  44. color: Colors.white,
  45. ),
  46. shape: CircleBorder(
  47. side: BorderSide(width: 2.0, color: Color(0xFFFFDFDFDF)),
  48. ),
  49. onPressed: () => setState(() => _count -= 1));
  50. }
  51. Widget _buildAddBtn() => MaterialButton(
  52. padding: EdgeInsets.all(0),
  53. textColor: Color(0xffFfffff),
  54. elevation: 3,
  55. color: Colors.blue,
  56. highlightColor: Color(0xffF88B0A),
  57. splashColor: Colors.red,
  58. child: Icon(
  59. Icons.add,
  60. color: Colors.white,
  61. ),
  62. shape: CircleBorder(
  63. side: BorderSide(width: 2.0, color: Color(0xFFFFDFDFDF)),
  64. ),
  65. onPressed: () => setState(() => _count += 1));
  66. }