| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- import 'package:flutter/cupertino.dart';
- import 'package:marquee/marquee.dart';
- class MarqueeText extends StatelessWidget {
- final String text;
- final TextStyle textStyle;
- final double velocity;
- final double blankSpace;
- const MarqueeText({
- super.key,
- required this.text,
- required this.textStyle,
- this.velocity = 18.0,
- this.blankSpace = 20.0,
- });
- Size _calculateTextSize(String text, TextStyle style) {
- final TextPainter textPainter = TextPainter(
- text: TextSpan(text: text, style: style),
- maxLines: 1,
- textDirection: TextDirection.ltr,
- )..layout(minWidth: 0, maxWidth: double.infinity);
- return textPainter.size;
- }
- @override
- Widget build(BuildContext context) {
- return LayoutBuilder(
- builder: (context, constraints) {
- final maxWidth = constraints.maxWidth; // 👈 父级能给的剩余宽度
- final textWidth = _calculateTextSize(text, textStyle).width;
- if (textWidth <= maxWidth) {
- return Text(
- text,
- style: textStyle,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- );
- } else {
- return SizedBox(
- width: maxWidth,
- child: Marquee(
- text: text,
- style: textStyle,
- blankSpace: blankSpace,
- pauseAfterRound: const Duration(seconds: 2),
- velocity: velocity,
- ),
- );
- }
- },
- );
- }
- }
|