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()
),
相关推荐
Zender Han6 小时前
Flutter 视频播放器——flick_video_player 介绍与使用
android·flutter·ios·音视频
恋猫de小郭11 小时前
Flutter Riverpod 3.0 发布,大规模重构下的全新状态管理框架
android·前端·flutter
RaidenLiu12 小时前
Riverpod 3:重建控制的实践与性能优化指南
前端·flutter
蒋星熠1 天前
Flutter跨平台工程实践与原理透视:从渲染引擎到高质产物
开发语言·python·算法·flutter·设计模式·性能优化·硬件工程
卢叁1 天前
Flutter之自定义TabIndicator
前端·flutter
萧雾宇1 天前
Android Compose打造仿现实逼真的烟花特效
android·flutter·kotlin
拜无忧1 天前
【教程】flutter常用知识点总结-针对小白
android·flutter·android studio
拜无忧1 天前
【教程】Flutter 高性能项目架构创建指南:从入门到高性能架构
android·flutter·android studio
醉过才知酒浓1 天前
flutter 拦截返回按钮的方法(WillPopScope or PopScope)
flutter
傅里叶2 天前
sudo启动Flutter程序AMD初始化失败
linux·flutter