Created
January 7, 2022 16:43
-
-
Save rohan20/ab7b2d9650dc68f228f1b548dd383a37 to your computer and use it in GitHub Desktop.
Flutter Marquee text or normal Text as needed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:marquee/marquee.dart'; | |
/// Marquee text along Axis.horizontal for the purpose of the demo. | |
class MaybeMarqueeText extends StatelessWidget { | |
final String text; | |
final double height; | |
final double maxWidth; | |
const MaybeMarqueeText( | |
this.text, { | |
Key? key, | |
this.height = 30, | |
this.maxWidth = 100, | |
}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
const TextStyle textStyle = TextStyle(fontSize: 18, color: Colors.white); | |
return Container( | |
color: Colors.black54, | |
child: Builder( | |
builder: (context) { | |
if (_willTextOverflow(text: text, style: textStyle)) { | |
return SizedBox( | |
height: height, | |
width: maxWidth, | |
child: Center( | |
child: Marquee( | |
text: text, | |
style: const TextStyle(fontSize: 18, color: Colors.white), | |
blankSpace: maxWidth / 3, | |
velocity: 30, | |
pauseAfterRound: const Duration(milliseconds: 1500), | |
), | |
), | |
); | |
} else { | |
return SizedBox( | |
height: height, | |
width: maxWidth, | |
child: Center( | |
child: Text(text, maxLines: 1, style: textStyle, textAlign: TextAlign.center), | |
), | |
); | |
} | |
}, | |
), | |
); | |
} | |
// https://stackoverflow.com/questions/51114778/how-to-check-if-flutter-text-widget-was-overflowed | |
bool _willTextOverflow({required String text, required TextStyle style}) { | |
final TextPainter textPainter = TextPainter( | |
text: TextSpan(text: text, style: style), | |
maxLines: 1, | |
textDirection: TextDirection.ltr, | |
)..layout(minWidth: 0, maxWidth: maxWidth); | |
return textPainter.didExceedMaxLines; | |
} | |
} |
how to change background color
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See demo here and walkthrough: https://twitter.com/rohantaneja_/status/1479499425387003910