You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter点击按钮时如何为InteractiveViewer的Matrix4位移添加动画

实现方案

你目前是直接给TransformationController赋值导致跳转变换,只需要通过AnimationController驱动Matrix4Tween做矩阵插值,就能实现平滑的过渡动画,修改步骤如下:

步骤1:给State类混入Ticker提供者,声明动画控制器

class YourWidgetState extends State<YourWidget> with SingleTickerProviderStateMixin {
  // 你原有声明的变换控制器保留
  final TransformationController controller = TransformationController();
  // 新增动画相关控制器
  late AnimationController _animController;
  late Animation<Matrix4> _matrixAnim;
  // 你原有定义的width、gridboxwidth、gridboxheight等变量照常声明
  // ...
}

步骤2:初始化/销毁动画控制器

@override
void initState() {
  super.initState();
  _animController = AnimationController(
    vsync: this,
    duration: const Duration(milliseconds: 300), // 动画时长可自行调整
  );
  // 监听动画插值更新,实时同步到变换控制器
  _matrixAnim = AlwaysStoppedAnimation(Matrix4.identity());
  _matrixAnim.addListener(() {
    controller.value = _matrixAnim.value;
  });
}

@override
void dispose() {
  _animController.dispose();
  controller.dispose();
  super.dispose();
}

步骤3:封装通用动画执行方法

void _animateToMatrix(Matrix4 targetMatrix) {
  // 动画执行中触发新请求时,先停止旧动画避免冲突
  if (_animController.isAnimating) {
    _animController.stop();
  }
  // 配置矩阵插值规则和动画曲线
  _matrixAnim = Matrix4Tween(
    begin: controller.value,
    end: targetMatrix,
  ).animate(CurvedAnimation(
    parent: _animController,
    curve: Curves.easeInOut, // 可替换为其他动画曲线
  ));
  // 启动动画
  _animController.forward(from: 0);
}

步骤4:修改按钮触发逻辑

把原来直接赋值的逻辑替换为调用动画方法即可:

Row(
  children: [
    ElevatedButton(
      onPressed: () {
        _animateToMatrix(Matrix4.identity()..translate(0.0, 0.0));
      },
      child: const Text('<'),
    ),
    ElevatedButton(
      onPressed: () {
        _animateToMatrix(Matrix4.identity()..translate(-width, 0.0));
      },
      child: const Text('>'),
    ),
  ],
)

补充说明

你后续要扩展上下滚动功能时,只需要修改传入_animateToMatrix的目标矩阵translate方法的y轴参数即可,不需要修改动画底层逻辑。如果要避免动画执行过程中重复点击触发异常,可以在_animateToMatrix入口加动画状态判断,运行中直接返回即可。

内容的提问来源于stack exchange,提问作者vontdeux

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 02:18:04