Skip to content

Instantly share code, notes, and snippets.

@rohan20
Created January 7, 2022 16:43
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rohan20/ab7b2d9650dc68f228f1b548dd383a37 to your computer and use it in GitHub Desktop.
Save rohan20/ab7b2d9650dc68f228f1b548dd383a37 to your computer and use it in GitHub Desktop.
Flutter Marquee text or normal Text as needed
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;
}
}
@rohan20
Copy link
Author

rohan20 commented Jan 7, 2022

@theappideasankit
Copy link

how to change background color

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment