Flutter回顾#1:动画:

隐式动画

单Widget

flutter全自动控制单个Widgte变化,不需要开发者关心,常用于控件动画效果。

AnimatedContainer

Contianer对应动画组件是AnimatedContainer,热重载之后会看到代码改动之后的变化动画。注意,Container的color和decoration属性只能二选一,因为本身后者这就是前者的实现原理。

dart 复制代码
body: Center(
        child: AnimatedContainer(
          duration: Duration(milliseconds: 100),
          width: 300,
          height: _height,
          decoration: BoxDecoration(
            gradient: LinearGradient(        //渐变组件
              begin: Alignment.bottomCenter, //渐变起始色位置
                end: Alignment.topCenter,    //渐变终止色位置
                stops: [0.1,0.3],            //渐变出现的区间
                colors: [Colors.red, Colors.white]), //起始色和终止色
            boxShadow: [BoxShadow(
                spreadRadius: 20, //边框颜色粗细度
                blurRadius: 20)], //边框模糊粗细度
            borderRadius: BorderRadius.circular(150) //边框圆角半径
          ),
          child: Center(child: Text("HI", style: TextStyle(fontSize: 50))),
        ),
      ),

多Widget

AnimatedSwitcher

在多个Widget之间实现动画,常见的父Widget切换子Widget类型时,AnimatedSwitcher可以实现平滑过渡的动画效果,但要注意,AnimatedSwitcher只能让他的直接child切换类型(或者Key变化)时产生动画效果,结构上隔一代不会有效果,同类型同key也不会有效果。不同类型直接生效,同类型先看key,不一样的话也会生效。

dart 复制代码
child: AnimatedSwitcher(
  duration: Duration(milliseconds: 3000),
  child: _height > 400 ? Container(color: Colors.blue, width: 200, height: 200,)
      : CircularProgressIndicator()
),

动画效果实际上由AnimatedSwitcher的transitionBuilder来控制的,默认不指定会自动实现了FadeTransition,从而有了渐隐效果。RotationTransition、ScaleTransition等等,多个transitionBuilder可以嵌套组合实现复杂的多重效果。

dart 复制代码
child: AnimatedSwitcher(
            transitionBuilder: (child,animation){
              return FadeTransition(
                opacity: animation,
                child: ScaleTransition(scale: animation,
                  child: child,
                ),
              );
            },
              duration: Duration(milliseconds: 3000),
              child: Text(key: ValueKey(_height),"$_height",style: TextStyle(fontSize: 50),)
          ),
相关推荐
程序员老刘7 小时前
Flutter版本选择指南:尽早升级3.47.9 | 2026年11月
flutter·ai编程·客户端
恋猫de小郭15 小时前
Android Keep Rules 解读,直接影响 Google Play 上架和曝光
android·前端·flutter
恋猫de小郭2 天前
Flutter A2UI 1.0 ,原来的 genui 也正式换成了这一套 SDK 了
android·前端·flutter
LinXunFeng2 天前
A2UI 1.0 详解:让 AI 生成 Flutter 界面,还不怕它乱写
前端·flutter·agent
好的佩奇2 天前
Dart 之元数据与注解
android·flutter·dart
恋猫de小郭5 天前
Jetpack Compose 1.13 发布,憋了这么久终有交代了
android·前端·flutter
好的佩奇5 天前
蓝牙之设备角色与连接
android·flutter·蓝牙
SoaringHeart6 天前
Flutter最佳实践:用 flutter_html 渲染富文本
前端·flutter
恋猫de小郭7 天前
Flutter 3.50.0 Release 的第一个崩溃,修好了,还没 hotfix
android·前端·flutter
程序员老刘7 天前
跨平台开发地图 | 2026年11月
flutter·ai编程·客户端