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

Flutter如何实现从左到右循环移动的动画Container?

效果预览图

Flutter 实现无限循环左右移动Container的方案

核心实现逻辑

使用Flutter自带的动画体系,通过AnimationController控制动画播放状态,配合SlideTransition实现Container的位移动画,开启repeat模式即可实现无限循环播放。

实现步骤

  • 在页面的State类中混入SingleTickerProviderStateMixin,为动画提供ticker驱动
  • 初始化AnimationController设置动画时长,调用repeat()方法开启无限循环
  • 通过Tween定义偏移量的变化区间,生成动画对象
  • 使用SlideTransition包裹目标Container,绑定动画对象即可生效

完整示例代码

import 'package:flutter/material.dart';

class RoomChatScreen extends StatefulWidget {
  const RoomChatScreen({super.key});

  @override
  State<RoomChatScreen> createState() => _RoomChatScreenState();
}

class _RoomChatScreenState extends State<RoomChatScreen> with SingleTickerProviderStateMixin {
  late AnimationController _animController;
  late Animation<Offset> _slideAnim;

  @override
  void initState() {
    super.initState();
    // 初始化动画控制器,3秒完成一次移动
    _animController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 3),
    );
    // 定义偏移规则:从屏幕左侧外移动到屏幕右侧外
    _slideAnim = Tween<Offset>(
      begin: const Offset(-1, 0),
      end: const Offset(1, 0),
    ).animate(_animController);
    // 开启无限循环
    _animController.repeat();
  }

  @override
  void dispose() {
    // 释放控制器避免内存泄漏
    _animController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("房间聊天页面")),
      body: SlideTransition(
        position: _slideAnim,
        child: Container(
          width: 120,
          height: 60,
          decoration: BoxDecoration(
            color: Colors.lightBlue,
            borderRadius: BorderRadius.circular(12),
          ),
          child: const Center(child: Text("移动元素", style: TextStyle(color: Colors.white, fontSize: 16))),
        ),
      ),
    );
  }
}

参数调整说明

  • 调整动画速度:修改AnimationController的duration参数,数值越小动画速度越快
  • 调整移动范围:修改Tween的begin和end的Offset值,Offset第一个参数为x轴偏移,0为屏幕初始位置,负数值向左偏移、正数值向右偏移
  • 调整循环间隔:给repeat方法传入period参数,可设置两次动画播放之间的停顿时长

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:06:03