我正在寻找一种在Text小部件上实现字幕样式的方法,以便当文本从屏幕溢出时自动开始滚动。 有没有办法做到这一点。 我尝试了所有装饰模式,但似乎无法在此处找到“字幕”选项。
答案 0 :(得分:4)
这个小部件是我想出的,我认为它可以满足您的需求:
class MarqueeWidget extends StatefulWidget {
final Widget child;
final Axis direction;
final Duration animationDuration, backDuration, pauseDuration;
MarqueeWidget({
@required this.child,
this.direction: Axis.horizontal,
this.animationDuration: const Duration(milliseconds: 3000),
this.backDuration: const Duration(milliseconds: 800),
this.pauseDuration: const Duration(milliseconds: 800),
});
@override
_MarqueeWidgetState createState() => _MarqueeWidgetState();
}
class _MarqueeWidgetState extends State<MarqueeWidget> {
ScrollController scrollController = ScrollController();
@override
void initState() {
scroll();
super.initState();
}
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: widget.child,
scrollDirection: widget.direction,
controller: scrollController,
);
}
void scroll() async {
while (true) {
await Future.delayed(widget.pauseDuration);
await scrollController.animateTo(
scrollController.position.maxScrollExtent,
duration: widget.animationDuration,
curve: Curves.easeIn);
await Future.delayed(widget.pauseDuration);
await scrollController.animateTo(0.0,
duration: widget.backDuration, curve: Curves.easeOut);
}
}
}
其功能应该非常明显。一个示例实现如下所示:
class FlutterMarqueeText extends StatefulWidget {
@override
_FlutterMarqueeTextState createState() => _FlutterMarqueeTextState();
}
class _FlutterMarqueeTextState extends State<FlutterMarqueeText> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter Marquee Text"),
),
body: Center(
child: SizedBox(
width: 200.0,
child: MarqueeWidget(
direction: Axis.horizontal,
child: Text(
"This text is to long to be shown in just one line"))),
));
}
}
答案 1 :(得分:0)
您可以使用 marquee 包
marquee
无限滚动文本的小部件。提供许多自定义设置,包括自定义滚动方向、持续时间、曲线以及每轮后的暂停。
在 pubspec.yaml 文件中使用添加的 marquee
依赖项
dependencies:
marquee: ^2.1.0
要将依赖项导入您的文件,请使用以下代码行:
import 'package:marquee/marquee.dart';
你可以这样使用它,这很简单,没有任何参数属性
Marquee(
text: 'There once was a boy who told this story about a boy',
)
您还可以使用如下所示的一些属性和可定制性
Marquee(
text: 'Some sample text that takes some space.',
style: TextStyle(fontWeight: FontWeight.bold),
scrollAxis: Axis.horizontal,
crossAxisAlignment: CrossAxisAlignment.start,
blankSpace: 20.0,
velocity: 100.0,
pauseAfterRound: Duration(seconds: 1),
startPadding: 10.0,
accelerationDuration: Duration(seconds: 1),
accelerationCurve: Curves.linear,
decelerationDuration: Duration(milliseconds: 500),
decelerationCurve: Curves.easeOut,
)