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_flavorizr 多渠道打包
前端·flutter
G_dou_2 天前
# Flutter+OpenHarmony 实战:note_app 笔记应用
flutter·harmonyos
西西学代码2 天前
Flutter---侧边栏会话列表
flutter
G_dou_2 天前
Flutter+OpenHarmony实战:Calculator 计算器项目
flutter
小小小小小鹿2 天前
# Vibe Coding 实战:Flutter 滑动列表上的花式动效
flutter·vibecoding
西西学代码2 天前
Flutter---登录弹窗
flutter
G_dou_2 天前
# Flutter+OpenHarmony 实战:ToDo待办清单
flutter·harmonyos
不爱吃糖的程序媛2 天前
Flutter 三方库适配鸿蒙教程
flutter·华为·harmonyos
2501_919749032 天前
鸿蒙 Flutter 实战:video_compress 3.1.4 适配 3.27-ohos 全流程
flutter·华为·harmonyos