marquee_text.dart 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import 'package:flutter/cupertino.dart';
  2. import 'package:marquee/marquee.dart';
  3. class MarqueeText extends StatelessWidget {
  4. final String text;
  5. final TextStyle textStyle;
  6. final double velocity;
  7. final double blankSpace;
  8. const MarqueeText({
  9. super.key,
  10. required this.text,
  11. required this.textStyle,
  12. this.velocity = 18.0,
  13. this.blankSpace = 20.0,
  14. });
  15. Size _calculateTextSize(String text, TextStyle style) {
  16. final TextPainter textPainter = TextPainter(
  17. text: TextSpan(text: text, style: style),
  18. maxLines: 1,
  19. textDirection: TextDirection.ltr,
  20. )..layout(minWidth: 0, maxWidth: double.infinity);
  21. return textPainter.size;
  22. }
  23. @override
  24. Widget build(BuildContext context) {
  25. return LayoutBuilder(
  26. builder: (context, constraints) {
  27. final maxWidth = constraints.maxWidth; // 👈 父级能给的剩余宽度
  28. final textWidth = _calculateTextSize(text, textStyle).width;
  29. if (textWidth <= maxWidth) {
  30. return Text(
  31. text,
  32. style: textStyle,
  33. maxLines: 1,
  34. overflow: TextOverflow.ellipsis,
  35. );
  36. } else {
  37. return SizedBox(
  38. width: maxWidth,
  39. child: Marquee(
  40. text: text,
  41. style: textStyle,
  42. blankSpace: blankSpace,
  43. pauseAfterRound: const Duration(seconds: 2),
  44. velocity: velocity,
  45. ),
  46. );
  47. }
  48. },
  49. );
  50. }
  51. }