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()
),
相关推荐
勤劳打代码2 天前
Flutter 架构日记 — 状态管理
flutter·架构·前端框架
比特鹰3 天前
手把手带你用Flutter手搓人生K线
前端·javascript·flutter
火柴就是我3 天前
Flutter限制输入框只能输入中文,iOS拼音打不出来?
flutter
TT_Close4 天前
【Flutter×鸿蒙】debug 包也要签名,这点和 Android 差远了
android·flutter·harmonyos
TT_Close4 天前
【Flutter×鸿蒙】FVM 不认鸿蒙 SDK?4步手动塞进去
flutter·swift·harmonyos
TT_Close4 天前
【Flutter×鸿蒙】一个"插队"技巧,解决90%的 command not found
flutter·harmonyos
恋猫de小郭4 天前
Flutter 发布官方 Skills ,Flutter 在 AI 领域再添一助力
android·前端·flutter
恋猫de小郭5 天前
2026 Flutter VS React Native ,同时在 AI 时代 VS Native 开发,你没见过的版本
android·前端·flutter
明君879975 天前
Flutter 如何给图片添加多行文字水印
前端·flutter
四眼肥鱼6 天前
flutter 利用flutter_libserialport 实现SQ800 串口通信
前端·flutter