flutter如何实现marquee效果
在Flutter中如何实现文字的跑马灯(Marquee)效果?我尝试了SingleChildScrollView配合AnimatedBuilder,但横向滚动时文本无法循环播放。官方好像没有提供现成的Marquee组件,有没有稳定可靠的第三方库推荐?或者如何通过自定义动画实现无限循环的横向滚动效果?最好能支持控制滚动速度、暂停和方向调整。
2 回复
Flutter中实现跑马灯效果可使用SingleChildScrollView结合AnimationController。设置水平滚动,通过动画控制scrollController.offset实现循环滚动。也可使用第三方库如marquee简化实现。
更多关于flutter如何实现marquee效果的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中实现跑马灯(Marquee)效果可以通过多种方式实现,以下是几种常见的方法:
方法一:使用 marquee 包(推荐)
- 在
pubspec.yaml中添加依赖:
dependencies:
marquee: ^2.2.1
- 在代码中使用:
import 'package:marquee/marquee.dart';
Marquee(
text: '这是一个跑马灯文本,当文本过长时会自动滚动显示',
style: TextStyle(fontSize: 16, color: Colors.black),
scrollAxis: Axis.horizontal, // 水平滚动
crossAxisAlignment: CrossAxisAlignment.start,
blankSpace: 20.0, // 文本间的空白
velocity: 50.0, // 滚动速度
pauseAfterRound: Duration(seconds: 1), // 每轮滚动后的暂停时间
startPadding: 10.0,
accelerationDuration: Duration(seconds: 1),
accelerationCurve: Curves.linear,
decelerationDuration: Duration(milliseconds: 500),
decelerationCurve: Curves.easeOut,
)
方法二:使用 AnimationController 自定义实现
import 'package:flutter/material.dart';
class CustomMarquee extends StatefulWidget {
final String text;
final TextStyle style;
const CustomMarquee({super.key, required this.text, required this.style});
@override
_CustomMarqueeState createState() => _CustomMarqueeState();
}
class _CustomMarqueeState extends State<CustomMarquee> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<Offset> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(seconds: 10),
vsync: this,
)..repeat();
_animation = Tween<Offset>(
begin: const Offset(1.0, 0.0),
end: const Offset(-1.0, 0.0),
).animate(_controller);
}
@override
Widget build(BuildContext context) {
return SizedBox(
height: 30,
child: SlideTransition(
position: _animation,
child: Text(
widget.text,
style: widget.style,
overflow: TextOverflow.visible,
),
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
// 使用
CustomMarquee(
text: '自定义跑马灯效果',
style: TextStyle(fontSize: 16, color: Colors.blue),
)
方法三:使用 ListView 实现
Widget buildMarqueeWithListView(String text) {
return SizedBox(
height: 30,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
Text(
text,
style: TextStyle(fontSize: 16),
),
],
),
);
}
推荐使用 marquee 包,因为它功能完善、配置灵活,支持暂停、速度控制等特性,且性能较好。如果需求简单,也可以选择自定义实现的方式。

