Flutter:AnimatedSwitcher当子元素改变时,触发动画

html 复制代码
AnimatedSwitcher中的子元素
由:CircularProgressIndicator()
改变为:Image.network('https://cdn.uviewui.com/uview/swiper/1.jpg')
则会触发动画
js 复制代码
class _MyHomePageState extends State<MyHomePage> {
  bool flag = true;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('标题'),
      ),
      body: Center(
        child: Container(
          alignment: Alignment.center,
          width: 400,
          height: 200,
          color: Colors.yellowAccent,
          child: AnimatedSwitcher(
            duration: const Duration(milliseconds: 500),
            child: flag ? const CircularProgressIndicator() : Image.network('https://cdn.uviewui.com/uview/swiper/1.jpg'),
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          flag = !flag;
          setState(() {});
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}

AnimatedSwitcher中通过添加transitionBuilder修改动画效果

js 复制代码
// 添加1个缩放动画
child: AnimatedSwitcher(
transitionBuilder:((child, animation){ // 改变动画效果
    return ScaleTransition( // 缩放
      scale: animation,
      child: child,
    );
  }),
  duration: const Duration(milliseconds: 500),
  child: flag ? const CircularProgressIndicator() : Image.network('https://cdn.uviewui.com/uview/swiper/1.jpg'),
),

// 动画也可以叠加使用,在添加一个淡入淡出
child: AnimatedSwitcher(
  transitionBuilder:((child, animation){ // 改变动画效果
    return ScaleTransition( // 缩放
      scale: animation,
      child: FadeTransition(opacity: animation,child: child,), // 淡入淡出
    );
  }),
  duration: const Duration(milliseconds: 500),
  child: flag ? const CircularProgressIndicator() : Image.network('https://cdn.uviewui.com/uview/swiper/1.jpg'),
),

AnimatedSwitcher里如果是改变同样的组件,如何触发动画

js 复制代码
// 相同组件,只是内容更换,需要加key: UniqueKey()唯一的
child: Text(
  flag ? "你好Flutter" : "改变内容",
  key: UniqueKey()
),
相关推荐
liulian091612 分钟前
Flutter for OpenHarmony 跨平台开发:颜色选择器功能实战指南
flutter
liulian09165 小时前
Flutter for OpenHarmony 跨平台开发:BMI计算器功能实战指南
flutter·华为
xmdy58668 小时前
Flutter+开源鸿蒙实战|智安盾电商溯源平台Day1 项目搭建与整体方案拆解
flutter·开源·harmonyos
小白640213 小时前
AI辅助设计Flutter蓝牙自动连接系统
人工智能·flutter
xmdy586614 小时前
Flutter+开源鸿蒙实战|智联邻里Day6 引入GetX全局架构+升级版下拉刷新+Toast弹窗+网络状态监听
flutter·开源·harmonyos
xmdy586614 小时前
Flutter+开源鸿蒙实战|智联邻里Day5 闲置详情页+删除功能+下拉刷新+交互优化
flutter·开源·harmonyos
maaath15 小时前
【maaath】Flutter for OpenHarmony 媒体工具应用开发实战
flutter·华为·harmonyos
maaath16 小时前
【maaath】 Flutter for OpenHarmony 快捷工具箱应用实战开发
flutter·华为·harmonyos
maaath16 小时前
【maaath】Flutter for OpenHarmony 实战:茶叶茶艺应用开发详解
flutter·华为·harmonyos
maaath16 小时前
【maaath】Flutter for OpenHarmony 的手办展示应用开发实践
flutter·华为·harmonyos