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()
),
相关推荐
dragon7253 小时前
关于image组件设置宽高不生效问题的探究
flutter
会煮咖啡的猫4 小时前
Flutter 是否需要 UI 组件库?
flutter
眼镜会飞4 小时前
Flutter 3.x新版android端的build.gradle.kts文件配置arm64-v8a和armeabi-v7a等
android·前端·flutter
恋猫de小郭5 小时前
Flutter 小技巧之有趣的 UI 骨架屏框架 skeletonizer
android·前端·flutter
一狐九6 小时前
Flutter如何通过GlobalKey调用组件内的方法
前端·flutter
张风捷特烈7 小时前
鸿蒙纪·Flutter卷#03 | 从配置证书到打包发布
android·flutter·harmonyos
RaidenLiu1 天前
从 Provider 迈向 Riverpod 3:核心架构与迁移指南
前端·flutter
叽哥1 天前
Flutter面试:Dart基础2
flutter·面试·dart
tangweiguo030519871 天前
Android原生(Kotlin)与Flutter混合开发 - 设备控制与状态同步解决方案
android·flutter
江上清风山间明月2 天前
Flutter AlwaysScrollableScrollPhysics详解
flutter·滚动·scrollable·scrollphysics